Archive for November, 2010

Design Patterns Reference: Proxy

Monday, November 29th, 2010

The Proxy Design Pattern buils an object that is positioned transparently within two other objects in order to intercept or proxy the communication or access.

 

class CD
{
protected $_title = ”;
protected $_band = ”;
protected $_handle = null;

 

public function __construct($title, $band)
{
$this->_title = $title;
$this->_band = $band;
}

 

public function buy()
{
$this->_connect();

 

$query = “update CDs set bought=1 where band='”;
$query .= mysql_real_escape_string($this->_band, $this->_handle);
$query .= “‘ and title='”;
$query .= mysql_real_escape_string($this->_title, $this->_handle);
$query .= “‘”;

 

mysql_query($query, $this->_handle);
}

 

protected function __connect()
{
$this->_handle = mysql_connect(‘localhost’, ‘user’, ‘pass’);
mysql_select_db(‘CD’, $this->_handle);
}
}

 

// CD class simply takes a band and title, updates the DB, and completes the sale
$externalTitle = “Waste of a Rib”;
$externalBand = ‘Never Again’;

 

$cd = new CD($externalTitle, $externalBand);
$cd->buy();

 

// A new store in another city will leverage this now via Proxy
// simply by overwriting the protected connect method of the CD class

class DallasNOCCDProxy extends CD
{
protected function __connect()
{
$this->_handle = mysql_connect(‘dallas’, ‘user’,’pass’);
mysql_select_db(‘CD’);
}
}

 

$externalTitle = “Waste of a Rib”;
$externalBand = ‘Never Again’;

 

$cd = new DallasNOCCDProxy($externalTitle, $externalBand);
$cd->buy();

 

source: http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470496703,descCd-DOWNLOAD.html

 

 

PHP Ternary Conditionals quick reference

Monday, November 29th, 2010

with variable:

 

$greeting = (date(“G”) < 12) ? ‘Good morning’ : ‘Good afternoon’;
echo $greeting;

 

without:

 

echo (date(“G”) < 12) ? ‘Good morning’ : ‘Good afternoon’;

 

another great example
courtesy of:

http://www.addedbytes.com/php/ternary-conditionals/
alternate color with ternary and modulus:

 

$i = 1;
echo ‘<table>’;
while ($data = mysql_fetch_array($result))
{
echo ‘ <tr>’;
echo ‘ <td bgcolor=”‘;
echo (($i % 2) == 0) ? ‘#eee’ : ‘#ddd’ ;
echo ‘”>’;
echo $data[‘field’];
echo ‘ </td>’;
echo ‘ </tr>’;
$i++;
}
echo ‘</table>’;

 

/* another basic usage */
courtesty of:
http://davidwalsh.name/php-shorthand-if-else-ternary-operators

 

$message = ‘Hello ‘.($user->is_logged_in() ? $user->get(‘first_name’ )  :  ‘Guest’ ) ;

 

also see:
http://php.net/manual/en/language.operators.comparison.php
for more examples,
search the page (F3 in FF) for ternary

 

another nice example from:
http://deadlytechnology.com/web-development-tips/php-ternary-syntax/

 

instead of:

 

$bTest1 = false;
$bTest2 = false;

 

if ($bTest1) {
if ($bTest2) {
echo ‘test 1 true, test 2 true’;
}
else {
echo ‘test 1 true, test 2 false’;
}
}
else {
if ($bTest2) {
echo ‘test 1 false, test 2 true’;
}
else {
echo ‘test 1 false, test 2 false’;
}
}

 

better:

 

echo $bTest1 ? ( $bTest2? ‘test 1 true, test 2 true’ : ‘test 1 true, test 2 false’ ) : ( $bTest2 ? ‘test 1 false, test 2 true ‘ : ‘test 1 false, test 2 false ‘
) ;

Design Patterns Reference: Prototype

Sunday, November 28th, 2010

“In situations where a resource intensive object needs to be created often, the Prototype Pattern provides a welcome route to faster execution.”

 

“The Prototype Design Pattern creates objects in such a way that an initial object or prototype can be copied and cloned more efficiently than creating a new instance.”

 

class CD
{
public $band = ”;
public $title = ”;
public $trackList = array();

public function __construct($id)
{
$handle = mysql_connect(‘localhost’, ‘user’, ‘pass’);
mysql_select_db(‘CD’, $handle);

$query = “select band, title, from CDs where id={$id}”;

$results = mysql_query($query, $handle);

if ($row = mysql_fetch_assoc($results)){
$this->band = $row[‘band’];
$this->title = $row[‘title’];
}
}

 

public function buy()
{
// cd buying magic here
var_dump ($this);
}
}

 

class MixtapeCD extends CD
{
public function __close()
{
$this->title = ‘Mixtape’;
}
}

 

$externalPurchaseInfoBandID = 12;
$bandMixProto = new MixtapeCD($externalPurchaseInfoBandID);

 

$externalPurchaseInfo = array();
$externalPurchaseInfo[] = array(‘brrr’, ‘goodbye’);
$externalPurchaseInfo[] = array(‘what it means’, ‘brrr’);

 

foreach ($externalPurchaseInfo as $mixed) {
$cd = clone $bandMixProto;
$cd->trackList = $mixed;
$cd->buy();
}

 

“When working with objects whose creation is expensive and whose initial configuration stays relatively the same through new instances, using duplicate classes made with the Prototype Design Pattern is best practice.”

 

source: http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470496703,descCd-DOWNLOAD.html

 

 

jQuery check if image with specific source exists on page

Thursday, November 18th, 2010

$(document).ready(function() {

$(“img”).each(function(){
imgtofind = “http://alexyz.com/images/example.jpg”;
source = $(this).attr(‘src’);
if(source == imgtofind){
alert(source); // or otherwise
}
});

}

Using folder structure, URL, instead of parameters, setup a virtual host, apache httpd-vhosts.conf, and then grab the url via PHP

Wednesday, November 17th, 2010

This post is about creating a small application in a folder, that behaves like Zend, or you could also say that it behaves like a service, in that it uses (converts) the folder structure of the url for the application’s use, rather than passing it url parameters. Another common example of such a system is employed by WordPress when “clean urls” is turned on.

 

Instead of this: http://alexyz.com?someparameter=something

We want this: http://alexyz.com/something

 

PHP then acquires that last value (call it a “command” or an “action” or whatever you’d like) and proceeds…

 

First, setup an apache virtual host, so that everything after the folder your app will live in is redirected back to that folder’s index along with any following parameters.  You do this via httpd-vhosts.conf

 

example contents of httpd-vhosts.conf (there are several virtual host projects in this example, for independant Zend applications, the code relevant to this lesson is red):

 

# Setup Listening Port
NameVirtualHost *:80

# Ensure “localhost” is preserved
<VirtualHost *:80>
ServerName localhost
DocumentRoot “C:\xampp\htdocs”

<Location /html/bonus>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ – [NC,L]
RewriteRule ^.*$ /html/bonus/index.php [NC,L]
</Location>

</VirtualHost>

# Setup “components” Virtual Host
<VirtualHost *:80>
ServerName components
DocumentRoot “C:\xampp\htdocs\components\public”

<Directory “C:\xampp\htdocs\components\public”>
Options Indexes FollowSymLinks Includes
AllowOverride All
Order allow,deny
Allow from all
</Directory>
RewriteEngine off

<Location />
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ – [NC,L]
RewriteRule ^.*$ index.php [NC,L]
</Location>

</VirtualHost>

# Setup “myzendresource” Virtual Host
<VirtualHost *:80>
ServerName myzendresource
DocumentRoot “C:\xampp\htdocs\myzendresource\public”
<Directory “C:\xampp\htdocs\myzendresource\public”>
Options Indexes FollowSymLinks Includes
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>

# Setup “datamodels” Virtual Host
<VirtualHost *:80>
ServerName datamodels
DocumentRoot “C:\xampp\htdocs\datamodels\public”
<Directory “C:\xampp\htdocs\datamodels\public”>
Options Indexes FollowSymLinks Includes
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>

 

So, any Url after /bonus, in this example, like: http://www.alexyz.com/bonus/something

will be pointed back to /bonus/index.php by apache for us.

 

Next, we simply grab that last part of the url in our index.php (in this example it’s the value “something”).  There are many ways we could do this, the example here is a very basic implementation of one way we might grab that value and proceed…

 

< ? php

$parameters = explode(“/”, $_SERVER[“REQUEST_URI”]);
foreach($parameters as $param){
if($param != NULL) { // This won’t fire if there is a terminating slash, we don’t want to set the parameter to empty!

$bonus_parameter = $param;

}
}

 

// now we can proceed with index.php just as though we’d done this, but we haven’t…:

 

$param = $_GET[‘parameterName’];

 

 

MySQL optimization refresher notes

Wednesday, November 17th, 2010

reference: http://www.databasejournal.com/features/mysql/article.php/10897_1382791_1/Optimizing-MySQL-Queries-and-Indexes.htm

Notes from above reference:

  • place EXPLAIN before your SELECT and learn a lot!
  • index index index…
  • in query, if possible, leave indexed field (usually after WHERE…) alone, or else every record must be calculated prior to conditional analysis…
  • ANALYZE TABLE tablename;
  • OPTIMIZE TABLE tablename
[quote block]

EXPLAIN SELECT employee_number,firstname,surname
FROM employee
WHERE employee_number= '10875';
+--------+----+-------------+----+-------+----+---+---------+
|table   |type|possible_keys|key |key_len|ref |rows| Extra  |
+--------+----+-------------+----+-------+----+---+---------+
|employee|ALL |NULL         |NULL|   NULL|NULL|  2|whereused|
+--------+----+-------------+----+-------+----+---+---------+

So what are all these things?

  • table shows us which table the output is about (for when you join many tables in the query)
  • type is an important one – it tells us which type of join is being used. From best to worst the types are: system, const, eq_ref, ref, range, index, all
  • possible_keys Shows which possible indexes apply to this table
  • key And which one is actually used
  • key_len give us the length of the key used. The shorter that better.
  • ref Tells us which column, or a constant, is used
  • rows Number of rows mysql believes it must examine to get the data
  • extra Extra info – the bad ones to see here are “using temporary” and “using filesort”

[quote block end]

jQuery select anchor tags that contain specific text, then change id, onClick (Capitalized!!!!), href, :contains, .attr(), .each()

Wednesday, November 17th, 2010

Easy actually, on load, select an anchor tag (or several, and do the following for .each()), that contains, among other contents, the word ‘Read’,

then set its id attribute, a Mouse event, and alter its href value:

$(document).ready(function(){

$(“a:contains(‘Read’)”).each(function(){

$(this).attr(‘id‘,’newid’);

$(this).attr(‘onClick‘, ‘return false;’); // Capitalize the C!!!!

$(this).attr(‘href‘, ‘http://www.alexyz.com’);

});

});

// alternatively, line them all up like this:

$(this).attr(‘id‘,’newid’).attr(‘onClick‘,’return false;’).attr(‘href‘,’http://www.alexyz.com’);

 

// UPDATE: Better method

$(“a[href*=‘search phrase’]”).each(function(){
var postId = $(this).attr(“href”).split(‘?’)[1].split(‘=’)[1].split(‘#’)[0]; // of course this will vary by need
$(this).attr(“href“,”?version=full&source=folder&post=”+postId);
});

Design Patterns Reference: Observer

Sunday, November 14th, 2010

The Observer Design Pattern facilitates the creation of objects that watch the state of a target object and provides state targeted functionality that is uncoupled from the core object.

The most obvious example, applications that support some type of plugin system.  Another example, cache systems, or message notification (example, members are notified when an item is in stock, to add that members may also be notified when it’s out of stock, simply add another observer, or perhaps another that texts them rather than emailing them…and so on).

When adding features to software that are activated by an action or state change but are loosely coupled, objects based on the Observer Design Pattern should be created.

MyObject is the Observable object.  It contains a protected array of observers. A public method addObserver() takes an instance of an observer and stores it in the array.

A public method doSomething() applies a state change to MyObject, whose notify() public method then loops through the array of observers.

Each such MyObjectObserver has a public method change(), that accepts an instance of MyObject, which modifies said object via a notify() method of MyObject that calls MyObjectObserver’s change() method directly as it’s encountered in the array of observers.

class CD
{
public $title = ”;
public $band = ”;
protected $_observers = array();

public function __construct($title, $band)
{
$this->title = $title;
$this->band = $band;
}

public function attachObserver($type, $observer)
{
$this->_observers[$type][] = $observer;
}

public function notifyObserver($type)
{
if(isset($this->_observers[$type])){
foreach($this->_observers[$type] as $observer)
{
$observer->update($this);
}
}
}

public function buy()
{
// stub actions of buying
$this->notifyObserver(‘purchased’);
}
}

class buyCDNotifyStreamObserver
{
public function update(CD $cd)
{
$activity = “The CD named {$cd->title} by “;
$activity .= “{$cd->band} was just purchased.”;
activityStream::addNewItem($activity);
}
}

class activityStream
{
public static function addNewItem($item)
{
// stub functions
print $item;
}
}

$title = “Wast of a Rib”;
$band = ‘Never Again’;
$cd = new CD($title, $band);

$observer = new buyCDNotifyStreamOberver();
$cd->attachObserver(‘purchased’, $observer);
$cd->buy();

source: http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470496703,descCd-DOWNLOAD.html

Support Prototype script.aculo.us and jQuery, page built with Prototype now being pulled into page that uses jQuery

Tuesday, November 2nd, 2010

So I developed a handful of sites several years ago using Prototype and script.aculo.us,

but now they’re being pulled into/included/required by pages, a site, that is strictly jQuery,

so I need to amend the Prototype site’s functions to check which library is loaded and then act accordingly.

It begs the question, if I were doing this completely fresh, which pattern (see Design Pattern posts) would I attempt to employ…? For example, I’d love to have the option right now to simply write an adapter pattern function instead of burying this conditional within each function…

Aside from Namespacing either or both libraries of course…

Example:

<script>
accordianing = false;
function comments_cabinet()
{
if(accordianing == true)
{
setTimeout( function() { accordian(); }, 25);
}
else
{
accordianing = true;
/* scriptaculous */
if(window.Prototype)
{

if($(‘comments_button’).style.display == ‘none’) // notice the Prototype standard $(”)
{
new Effect.BlindDown(‘comments_button’, {
duration: 0.5,
afterFinish: function(){
accordianing = false;
}
});
}
else
{
new Effect.BlindUp(‘comments_button’, {
duration: 0.5,
afterFinish: function(){
accordianing = false;
}
});
}
}
else
{

$(‘#comments_button’).toggle(‘slow’); // otherwise, use the jQuery version $(‘#’)
accordianing = false;
}
return false;
}
}
</script>