<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>DiscDev</title>
	<atom:link href="http://discdev.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://discdev.com</link>
	<description>Disc Golf, Web Development, Real Estate Investment</description>
	<lastBuildDate>Tue, 08 Nov 2011 01:06:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to find out if your rental home is in foreclosure Clark County Nevada</title>
		<link>http://discdev.com/2011/10/04/how-to-find-out-if-your-rental-home-is-in-foreclosure-clark-county-nevada/</link>
		<comments>http://discdev.com/2011/10/04/how-to-find-out-if-your-rental-home-is-in-foreclosure-clark-county-nevada/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 21:53:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Real Estate Investment]]></category>
		<category><![CDATA[Clark County]]></category>
		<category><![CDATA[Foreclosure]]></category>
		<category><![CDATA[how-to-find-out-if-rental-is]]></category>
		<category><![CDATA[how-to-find-out-if-your-rental-is-in-foreclosure-las-vegas]]></category>
		<category><![CDATA[Rental]]></category>
		<category><![CDATA[rental-in-foreclosure-clark-county]]></category>

		<guid isPermaLink="false">http://discdev.com/?p=965</guid>
		<description><![CDATA[Steps to find out if your rental home is in foreclosure in Clark County, Nevada, Las Vegas, Henderson, Boulder City. First Go to the Clark County Assessor website and do a lookup of the address or owner and get the Parcel number. Then Go to the Clark County Recorder website and on the upper far [...]]]></description>
			<content:encoded><![CDATA[<iframe src="http://www.facebook.com/plugins/like.php?href=http://discdev.com/2011/10/04/how-to-find-out-if-your-rental-home-is-in-foreclosure-clark-county-nevada/&amp;layout=button_count&amp;show_faces=1&amp;width=450&amp;action=like&amp;colorscheme=light&amp;font=" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:25px"></iframe><p>Steps to find out if your rental home is in foreclosure in Clark County, Nevada, Las Vegas, Henderson, Boulder City.  First Go to the <a href="http://www.clarkcountynv.gov/depts/assessor/Pages/default.aspx" title="Clark County Assessor" target="_blank">Clark County Assessor</a> website and do a lookup of the address or owner and get the Parcel number.  Then Go to the <a href="http://www.clarkcountynv.gov/Depts/recorder/Pages/default.aspx" title="Clark County Recorder" target="_blank">Clark County Recorder</a> website and on the upper far left side of the site is &#8220;search records&#8221; click on that.  Enter the Parcel Number and do a search for foreclosure documents.</p>
<p>A more detailed description can be found <a href="http://www.clarkcountynv.gov/Depts/recorder/Pages/HomeForclosure.aspx" title="Rental homes in foreclosure">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://discdev.com/2011/10/04/how-to-find-out-if-your-rental-home-is-in-foreclosure-clark-county-nevada/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Speed up page loads using Cache PHP</title>
		<link>http://discdev.com/2011/09/30/speed-up-page-loads-using-cache-php/</link>
		<comments>http://discdev.com/2011/09/30/speed-up-page-loads-using-cache-php/#comments</comments>
		<pubDate>Fri, 30 Sep 2011 23:34:49 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Cache]]></category>
		<category><![CDATA[speed-up-php-using-memcached]]></category>
		<category><![CDATA[strtodate-in-croatian-not-working]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[ubuntu-memcache-server-2011]]></category>

		<guid isPermaLink="false">http://discdev.com/?p=946</guid>
		<description><![CDATA[At work we pull ranks for how key-phrases ranked on certain search engines once a week. We have many clients and each client has multiple key-phrases and each key-phrase has ranks for multiple search engines. This information is stored in the database. This information adds up more and more over time. So the longer a [...]]]></description>
			<content:encoded><![CDATA[<iframe src="http://www.facebook.com/plugins/like.php?href=http://discdev.com/2011/09/30/speed-up-page-loads-using-cache-php/&amp;layout=button_count&amp;show_faces=1&amp;width=450&amp;action=like&amp;colorscheme=light&amp;font=" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:25px"></iframe><p>At work we pull ranks for how key-phrases ranked on certain search engines once a week.   We have many clients and each client has multiple key-phrases and each key-phrase has ranks for multiple search engines.  This information is stored in the database.  This information adds up more and more over time.  So the longer a client is with us the more data that is stored in the database.  All this information can become cumbersome when trying to calculate and display each time a web page is loaded.  This is taxing on our web server to calculate this information and is also taxing on our database when all this information is pulled.   The solution to this problem is caching.  There are two types of caching we use at work.  Memcache and File caching.<span id="more-946"></span></p>
<p>Memcache is where the cache is stored on the web servers RAM.  This can be good because of the speed of retrieval of the cache.   The downfalls of using memcache is that if you restart the web server the information stored in RAM is lost.  Also the amount of information you can cache is limited to the size or your RAM on your web server.  The RAM limitation can be overcome by having a dedicated memcache server.  </p>
<p>File Caching is where the information is stored in a file on the web server.  This will be slower than memcache because the information is pulled from the hard drive of the web server instead of being pulled from the web servers RAM.   When the web server is restarted the cached information is not lost because it is stored on the hard drive.  The limitation of the size of all the caching is limited to the size of the hard drive and not the size of RAM on the web server.  Now with solid state hard drives coming out and getting cheaper all the time you can speed up the loading of file caches probably close to the speed of memcache.  </p>
<p>My first example will be memcaching.  In order to do memcaching on your web server you will have to make sure you have memcache installed.  I am running Ubuntu with LAMP, so the command line call to install memcache is &#8216;sudo apt-get install memcache&#8217;.  You can download my example file <a href='http://discdev.com/wp-content/uploads/2011/09/memcache_example.php_.tar.gz'>memcache_example.php.tar</a> so that you can follow along easier.  </p>
<p>I will not put all the code together for the memcaching example first and then break it down:</p>
<pre class="brush:php">
<?php
/**
* @author Phillip Brown, Developer <DiscDev.com>
* @date 2011-09-30
* @brief example of memcaching
*/
echo "
    &lt;html&gt;
        &lt;head&gt;
            &lt;title&gt;MemCache Example&lt;/title&gt;
        &lt;/head&gt;
        &lt;body&gt;
            &lt;h1&gt;MemCache Example&lt;/h1&gt;
";
if( isset($_GET['client_id']) &#038;&#038; is_numeric($_GET['client_id'])) {
    $client_id = $_GET['client_id'];
} else {
    $client_id = rand(1,20);
}

define('RANK_CACHE_DATE_STRING', 'next Saturday');

$memcache_obj = memcache_connect('localhost');
$cache_till = strtotime(RANK_CACHE_DATE_STRING);
$cache_name = 'rank_table_html_'.$client_id;
if( ! $html = memcache_get($memcache_obj, $cache_name)) {
    $html = get_rank_table_html($client_id);
    memcache_set($memcache_obj, $cache_name, $html, 0, $cache_till);
    echo "&lt;p&gt;";
    echo "There was NOT a cache of the HTML so new <br/>";
    echo "HTML was created and cached for next time <br/>";
    echo "this client is loaded.";
    echo "&lt;/p&gt;";
} else {
    echo "&lt;p&gt;There was a cache of the HTML&lt;/p&gt;";
}
echo $html;

function get_rank_table_html($client_id) {
    return "
                &lt;p&gt;
                    Here is where the table of ranks<br/>
                    would be for client# $client_id
                &lt;/p&gt;
            </body>
        </html>
    ";
}
?>
</pre>
<p>So in this example the first thing I do is define the client_id.  I have made it so you can use $_GET data or just let a random client id be created:</p>
<pre class="brush:php">
echo "
    &lt;html&gt;
        &lt;head&gt;
            &lt;title&gt;MemCache Example&lt;/title&gt;
        &lt;/head&gt;
        &lt;body&gt;
            &lt;h1&gt;MemCache Example&lt;/h1&gt;
";
if( isset($_GET['client_id']) &#038;&#038; is_numeric($_GET['client_id'])) {
    $client_id = $_GET['client_id'];
} else {
    $client_id = rand(1,20);
}
</pre>
<p>This next line of code should be in your  settings file where you would define constants and system settings.  the RANK_CACHE_DATE_STRING constant will define the string that phps strtotime will use to get the end date of the cache as a timestamp.  Since we pull ranks on Friday phps strtotime() function will use the string &#8216;next Saturday&#8217;.  This way the new cache will start Saturday morning at 12am.  By defining this once in your settings this can be changed in one place and will change throughout your system:</p>
<pre class="brush:php">
define('RANK_CACHE_DATE_STRING', 'next Saturday');
</pre>
<p>Next we will instantiate the memcache(<a href="http://us.php.net/manual/en/book.memcache.php" title="memcache" target="_blank">http://us.php.net/manual/en/book.memcache.php</a>):</p>
<pre class="brush:php">
$memcache_obj = memcache_connect('localhost');
</pre>
<p>Here we will use the  RANK_CACHE_DATE_STRING constant to create the $cache_till variable as a time stamp using phps strtotime function:</p>
<pre class="brush:php">
$cache_till = strtotime(RANK_CACHE_DATE_STRING);
</pre>
<p>Now we will define the $cache_name variable making sure it is distinct to the cache it will be referring to:</p>
<pre class="brush:php">
$cache_name = 'rank_table_html_'.$client_id;
</pre>
<p>Here is the conditional where we check to see if there is already a cache of the html we are looking for.  If there is then use that cached HTML otherwise create the HTML and cache it for next time:</p>
<pre class="brush:php">
if( ! $html = memcache_get($memcache_obj, $cache_name)) {
    $html = get_rank_table_html($client_id);
    memcache_set($memcache_obj, $cache_name, $html, 0, $cache_till);
    echo "&lt;p&gt;";
    echo "There was NOT a cache of the HTML so new <br/>";
    echo "HTML was created and cached for next time <br/>";
    echo "this client is loaded.";
    echo "&lt;/p&gt;";
} else {
    echo "&lt;p&gt;There was a cache of the HTML&lt;/p&gt;";
}
</pre>
<p>Now just echo out the HTML:</p>
<pre class="brush:php">
echo $html;
</pre>
<p>Here is the function that creates the HTML.  This is just generic for this example. </p>
<pre class="brush:php">
function get_rank_table_html($client_id) {
    // pull ranks from database
    // calculate ranks
    // create html from calculated ranks
    // return html
    return "
                &lt;p&gt;
                    Here is where the table of ranks<br/>
                    would be for client# $client_id
                &lt;/p&gt;
            </body>
        </html>
    ";
}
</pre>
<p>My second example will be file caching.  In order to do file caching you will have to make sure that the web server user has permissions to read and write to the folder that will contain the file caches.  You can download my example <a href='http://discdev.com/wp-content/uploads/2011/09/file_cache_example.tar.gz'>file_cache_example.tar</a> so that you can follow along easier.  </p>
<p>I will not put all the code together for the file caching example first and then break it down:</p>
<pre class="brush:php">
echo "
    &lt;html&gt;
        &lt;head&gt;
            &lt;title&gt;File Cache Example&lt;/title&gt;
        &lt;/head&gt;
        &lt;body&gt;
            &lt;h1&gt;File Cache Example&lt;/h1&gt;
";
if( isset($_GET['client_id']) &#038;&#038; is_numeric($_GET['client_id'])) {
    $client_id = $_GET['client_id'];
} else {
    $client_id = rand(1,20);
}
define('RANK_CACHE_DIRECTORY', 'cache/');
define('RANK_CACHE_DATE_STRING', 'next Saturday');
$cache_location_and_name =
    RANK_CACHE_DIRECTORY.
    date('Y-m-d', strtotime(RANK_CACHE_DATE_STRING)).
    '_'.
    'rank_table_html_'.
    $client_id;
if(file_exists($cache_location_and_name)) {
    $html = file_get_contents($cache_location_and_name);
    echo "&lt;p&gt;There was a cache of the HTML&lt;/p&gt;";
} else {
    $html = get_rank_table_html($client_id);
    file_put_contents(
       $cache_location_and_name,
       $html
    );
    echo "&lt;p&gt;";
    echo "There was NOT a cache of the HTML so new <br/>";
    echo "HTML was created and cached for next time <br/>";
    echo "this client is loaded.";
    echo "&lt;/p&gt;";
}
echo $html;
function get_rank_table_html($client_id) {
    return "
                &lt;p&gt;
                    Here is where the table of ranks<br/>
                    would be for client# $client_id
                &lt;/p&gt;
            </body>
        </html>
    ";
}
</pre>
<p>So again in this example the first thing I do is define the client_id.  I have made it so you can use $_GET data or just let a random client id be created:</p>
<pre class="brush:php">
echo "
    &lt;html&gt;
        &lt;head&gt;
            &lt;title&gt;File Cache Example&lt;/title&gt;
        &lt;/head&gt;
        &lt;body&gt;
            &lt;h1&gt;File Cache Example&lt;/h1&gt;
";
if( isset($_GET['client_id']) &#038;&#038; is_numeric($_GET['client_id'])) {
    $client_id = $_GET['client_id'];
} else {
    $client_id = rand(1,20);
}
</pre>
<p>Since we are caching to a folder on the web server we will define this location as a constant that should be defined where you define constants and system settings.</p>
<pre class="brush:php">
define('RANK_CACHE_DIRECTORY', 'cache/');
</pre>
<p>Again This next line of code should be in your  settings file where you would define constants and system settings.  the RANK_CACHE_DATE_STRING constant will define the string that phps strtotime will use to get the end date of the cache as a timestamp.  Since we pull ranks on Friday phps strtotime() function will use the string &#8216;next Saturday&#8217;.  This way the new cache will start Saturday morning at 12am.  By defining this once in your settings this can be changed in one place and will change throughout your system:</p>
<pre class="brush:php">
define('RANK_CACHE_DATE_STRING', 'next Saturday');
</pre>
<p>Now we will create a variable to hold a string defining the location and name of the cache.  You will notice that I start out the name of the cache with the date.    The date is defining when the cache will expire.  And again by putting the client id in the name of the cache we are making the name unique.</p>
<pre class="brush:php">
$cache_location_and_name =
    RANK_CACHE_DIRECTORY.
    date('Y-m-d', strtotime(RANK_CACHE_DATE_STRING)).
    '_'.
    'rank_table_html_'.
    $client_id;
</pre>
<p>Here we use a conditional to check for a cache of the HTML.  If there is a file with the same name and location of the file we just defined get the HTML contents of the file.  Otherwise create the HTML and save in a file as a cache for next time. The ingenious part is that once the now timestamp is greater than the timestamp of the cached file a new cached file will be created.</p>
<pre class="brush:php">
if(file_exists($cache_location_and_name)) {
    $html = file_get_contents($cache_location_and_name);
    echo "&lt;p&gt;There was a cache of the HTML&lt;/p&gt;";
} else {
    $html = get_rank_table_html($client_id);
    file_put_contents(
       $cache_location_and_name,
       $html
    );
    echo "&lt;p&gt;";
    echo "There was NOT a cache of the HTML so new <br/>";
    echo "HTML was created and cached for next time <br/>";
    echo "this client is loaded.";
    echo "&lt;/p&gt;";
}
echo $html;
</pre>
<p>Here is the function that is called from the first foreach to remove invalid files:</p>
<pre class="brush:php">
function remove_invalid_files($file) {
    return ! preg_match(
        '/\.|\.\.|\.svn/',
        $file
    );
}
</pre>
<p>One of the problems with file caching is that old cache files will build up on your web server over time.  In order to resolve this problem I have created a script that will remove old file caches from the web server.  This script will be run once a week from the web servers crontab. You can download my example <a href='http://discdev.com/wp-content/uploads/2011/09/file_cache_example.tar.gz'>file_cache_example.tar</a> so that you can follow along easier. </p>
<p>The first thing we want to do is define all the locations of the file caches that we want cleared out:</p>
<pre class="brush:php">
$cache_locations = array(
    'cache_folder' => '/cache/',
    //'rank_table'   => '/cache/rank_charts/',
    //'rank_chart'   => '/cache/rank_tables/'
);
</pre>
<p>Now we will create an array of files for each location:</p>
<pre class="brush:php">
$cached_file_lists = NULL;
foreach($cache_locations as $cache_name => $cache_location) {
    $files = scandir($cache_location);
    $files = array_filter($files, 'remove_invalid_files');
    $cached_file_lists[$cache_name]['location'] = $cache_location;
    $cached_file_lists[$cache_name]['files']    = $files;
}
</pre>
<p>Next we will do a foreach on each location and then do a foreach on each file in that location.  We will check each file to see if the data at the front of the file name is before now.  If it is then delete the file.</p>
<pre class="brush:php">
foreach($cached_file_lists as $cached_file_list_name => $data) {
    $location = $data['location'];
    foreach($data['files'] as $file_name) {
        preg_match(
            '(^[0-9]{4}-[0-9]{2}-[0-9]{2})',
            $file_name, $matches
        );
        if( ! empty($matches[0]) ) {
            $cache_end_date = strtotime($matches[0]);
        } else {
            $cache_end_date = FALSE;
        }
        if($cache_end_date &#038;&#038; $cache_end_date < strtotime('now')) {
            unlink($location.$file_name);
        }
    }
}
</pre>
<p>I will not put all the code together for the file cache clearing example:</p>
<pre class="brush:php">
$cache_locations = array(
    'cache_folder' => '/cache/',
    //'rank_table'   => '/cache/rank_charts/',
    //'rank_chart'   => '/cache/rank_tables/'
);
$cached_file_lists = NULL;
foreach($cache_locations as $cache_name => $cache_location) {
    $files = scandir($cache_location);
    $files = array_filter($files, 'remove_invalid_files');
    $cached_file_lists[$cache_name]['location'] = $cache_location;
    $cached_file_lists[$cache_name]['files']    = $files;
}
foreach($cached_file_lists as $cached_file_list_name => $data) {
    $location = $data['location'];
    foreach($data['files'] as $file_name) {
        preg_match(
            '(^[0-9]{4}-[0-9]{2}-[0-9]{2})',
            $file_name, $matches
        );
        if( ! empty($matches[0]) ) {
            $cache_end_date = strtotime($matches[0]);
        } else {
            $cache_end_date = FALSE;
        }
        if($cache_end_date &#038;&#038; $cache_end_date < strtotime('now')) {
            unlink($location.$file_name);
        }
    }
}
function remove_invalid_files($file) {
    return ! preg_match(
        '/\.|\.\.|\.svn/',
        $file
    );
}
</pre>
<p>So now on your web server create a crontab that will clear out all the old file caches every Saturday Morning at 6am.  The crontab file is usually located in the /etc folder.  So command like if you have vim installed, sudo vim /etc/crontab. Add the following lines:</p>
<pre>
# every Saturday Morning at 4am clear out all the old file caches.
0 4 * * 6 www-data cd /var/www/file_cache_example &#038;&#038; php file_cache_clearing_example.php
</pre>
<p>Make sure that the root user has permissions to read and write the cache folders.</p>
<p>This concludes todays lesson on caching.  Hope this has helped someone out there.  Please leave a comment if it has, or if you know a better way.</p>
]]></content:encoded>
			<wfw:commentRss>http://discdev.com/2011/09/30/speed-up-page-loads-using-cache-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Decorator pattern PHP</title>
		<link>http://discdev.com/2011/09/21/decorator-pattern-php/</link>
		<comments>http://discdev.com/2011/09/21/decorator-pattern-php/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 23:30:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[decorator-pattern-php]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[php-decorator]]></category>
		<category><![CDATA[php-decorator-pattern]]></category>

		<guid isPermaLink="false">http://discdev.com/?p=936</guid>
		<description><![CDATA[The Decorator Pattern uses composition and delegation instead of inheritance. Inheritance can lead to inflexibility, duplication, and an explosion of classes as your inheritance gets deeper and more complex. By using the Decorator Pattern we are able to modify the functionality of concrete components of a object at runtime. I am including two files that [...]]]></description>
			<content:encoded><![CDATA[<iframe src="http://www.facebook.com/plugins/like.php?href=http://discdev.com/2011/09/21/decorator-pattern-php/&amp;layout=button_count&amp;show_faces=1&amp;width=450&amp;action=like&amp;colorscheme=light&amp;font=" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:25px"></iframe><p>The Decorator Pattern uses composition and delegation instead of inheritance.  Inheritance can  lead  to inflexibility, duplication, and an explosion of classes as your inheritance gets deeper and more complex.  By using the Decorator Pattern we are able to modify the functionality of concrete components of a object at runtime.<span id="more-936"></span></p>
<p>I am including two files that go along with the example below.<br />
<a href='http://discdev.com/wp-content/uploads/2011/09/ship_inheritance.php_.tar.gz'>ship_inheritance.php.tar</a><br />
<a href='http://discdev.com/wp-content/uploads/2011/09/ship_decorator.php_.tar.gz'>ship_decorator.php.tar</a></p>
<p>The example I am going to use is a ship object that has health.  Now since I have been playing StarCraft II for the past couple of months I will be using types of ships from that game.  The three ships are Void Rays, Banshees, and Brood Lords.  Each of the ships start out with different healths.  There are other units in the game that have effects on the health of these ships.  These units are Probes and Marines.  Probes repair health while marines damage health(and yes I know that probes only repair health of  Protoss).</p>
<p>So lets start out creating classes using  inheritance so you can see the difference.  Our parent class will be the ship class and we will make it abstract so that all ship types that extend it will have to also have the abstract functionality that it defines.  </p>
<pre class="brush:php">
abstract class ship {
    abstract function get_health();
}
</pre>
<p>Next we will create  the three ship type classes that will extend the abstract ship class.  Each of these classes will have the get_health() function that is required by the abstract ship class that they extend.  You will notice that each ship type starts out with a default health as a member property called private $health.</p>
<pre class="brush:php">
class void_ray extends ship {
    private $health = 2;
    function get_health() {
        return $this->health;
    }
}

class banshee extends ship {
    private $health = 3;
    function get_health() {
        return $this->health;
    }
}

class brood_lord extends ship {
    private $health = 5;
    function get_health() {
        return $this->health;
    }
}
</pre>
<p>Now during a game these ship types health can be effected by probes and marines.  So in order to calculate the health of a ship after being effected by a probe or marine or both we will create classes that extend each ship type.</p>
<pre class="brush:php">
class probe_void_ray extends void_ray {
    function get_health() {
        return parent::get_health() + 1;
    }
}

class marine_void_ray extends void_ray {
    function get_health() {
        return parent::get_health() - 1;
    }
}

class marine_probe_void_ray extends void_ray {
    function get_health() {
        return parent::get_health() + 1 - 1;
    }
}

class probe_banshee extends banshee {
    function get_health() {
        return parent::get_health() + 1;
    }
}

class marine_banshee extends banshee {
    function get_health() {
        return parent::get_health() - 1;
    }
}

class marine_probe_banshee extends banshee {
    function get_health() {
        return parent::get_health() + 1 - 1;
    }
}

class probe_brood_lord extends brood_lord {
    function get_health() {
        return parent::get_health() + 1;
    }
}

class marine_brood_lord extends brood_lord {
    function get_health() {
        return parent::get_health() - 1;
    }
}

class marine_probe_brood_lord extends brood_lord {
    function get_health() {
        return parent::get_health() + 1 - 1;
    }
}
</pre>
<p>As you can see we are already venturing into inflexibility, duplication, and an explosion of classes.  Plus the naming of these classes are starting to get out of hand(Example: function marine_probe_void_ray()). Below is the code to see these classes in action.</p>
<pre class="brush:php">
echo "here is the inheritance example.<br/><br/>";
$ship = new void_ray();
echo "here is the health of a void ray ".$ship->get_health();
echo "<br/>";
$ship = new probe_void_ray();
echo "here is the health of a void ray that has ";
echo 'been repaired once by a probe '.$ship->get_health();
echo "<br/> ";
$ship = new marine_void_ray();
echo "here is the health of a void ray that has ";
echo 'been damaged once by a marine '.$ship->get_health();
echo "<br/> ";
$ship = new marine_probe_void_ray();
echo "here is the health of a void ray that has ";
echo "been damaged once by a marine and repaired ";
echo 'once by a probe '.$ship->get_health();
echo "<br/><br/>";

$ship = new banshee();
echo "here is the health of a banshee ".$ship->get_health();
echo "<br/> ";
$ship = new probe_banshee();
echo "here is the health of a banshee that has ";
echo 'been repaired once by a probe '.$ship->get_health();
echo "<br/> ";
$ship = new marine_banshee();
echo "here is the health of a banshee that has ";
echo 'been damaged once by a marine '.$ship->get_health();
echo "<br/> ";
$ship = new marine_probe_banshee();
echo "here is the health of a banshee that has ";
echo "been damaged once by a marine and repaired ";
echo 'once by a probe '.$ship->get_health();
echo "<br/><br/>";

$ship = new brood_lord();
echo "here is the health of a brood lord ".$ship->get_health();
echo "<br/> ";
$ship = new probe_brood_lord();
echo "here is the health of a brood lord that has ";
echo 'been repaired once by a probe '.$ship->get_health();
echo "<br/> ";
$ship = new marine_brood_lord();
echo "here is the health of a brood lord that has ";
echo 'been damaged once by a marine '.$ship->get_health();
echo "<br/> ";
$ship = new marine_probe_brood_lord();
echo "here is the health of a brood lord that has ";
echo "been damaged once by a marine and repaired ";
echo 'once by a probe '.$ship->get_health();
echo "<br/><br/>";
</pre>
<p>with an output of:</p>
<pre>
here is the health of a void ray 2
here is the health of a void ray that has been repaired once by a probe 3
here is the health of a void ray that has been damaged once by a marine 1
here is the health of a void ray that has been damaged once by a marine and repaired once by a probe 2

here is the health of a banshee 3
here is the health of a banshee that has been repaired once by a probe 4
here is the health of a banshee that has been damaged once by a marine 2
here is the health of a banshee that has been damaged once by a marine and repaired once by a probe 3

here is the health of a brood lord 5
here is the health of a brood lord that has been repaired once by a probe 6
here is the health of a brood lord that has been damaged once by a marine 4
here is the health of a brood lord that has been damaged once by a marine and repaired once by a probe 5
</pre>
<p>So in order to solve the problem of inflexibility, duplication, and an explosion of classes we turn to the Decorator Pattern.  With the Decorator Pattern example we will start out with a ship interface instead of a abstract ship.  We could have used an abstract ship but I feel it is better to use the interface.  With an interface all functions defined are automatically abstract and everything the implements it will also have to have those functions defined.  </p>
<pre class="brush:php">
interface ship {
    function get_health();
}
</pre>
<p>Next again we will define the three ship types.  These ship types will all implement the ship interface.  Again each must contain the get_health() function that is defined in the ship interface.  Each will also have the default health as a member property.</p>
<pre class="brush:php">
class void_ray implements ship {
    private $health = 2;
    function get_health() {
        return $this->health;
    }
}

class brood_lord implements ship {
    private $health = 3;
    function get_health() {
        return $this->health;
    }
}

class banshee implements ship {
    private $health = 5;
    function get_health() {
        return $this->health;
    }
}
</pre>
<p>Now with the Decorator Pattern an decorator enabler is needed.  The decorator enabler will be of the same type as the class that is being decorated.  In this case the enabler and the class being decorated both implement the ship interface.  The decorator enabler will accept another ship object in its constructor that will be saved as a member property.  The ship decorator enabler class will also have to contain the get_health() function that is mandated by the ship interface.</p>
<pre class="brush:php">
class ship_decorator_enabler implements ship {
    protected $ship;
    function __construct($ship) {
        $this->ship = $ship;
    }
    function get_health() {
        return $this->ship->get_health();
    }
}
</pre>
<p>Next we have the decorator classes themselves, probe and marine.  These decorator classes extend the ship decorator enabler class.  By extending the ship decorator enabler class we are able to refer to the ship object that was passed to the enabler in the get_health() function.</p>
<pre class="brush:php">
//probes repair health
class probe_decorator extends ship_decorator_enabler {
    function get_health() {
        return $this->ship->get_health() + 1;
    }
}

// marines damage health
class marine_decorator extends ship_decorator_enabler {
    function get_health() {
        return $this->ship->get_health() - 1;
    }
}
</pre>
<p>Below is the code to see these classes in action.</p>
<pre class="brush:php">
$ship = new void_ray();
echo 'void ray health '.
$ship->get_health()."<br/>";//2
$ship = new probe_decorator(
    new void_ray()
);
echo 'void ray health with probe decoration '.
$ship->get_health()."<br/>";//3
$ship = new marine_decorator(
    new void_ray()
);
echo 'void ray health with marine decoration '.
$ship->get_health()."<br/>";//1
$ship = new probe_decorator(
    new marine_decorator(
        new void_ray()
    )
);
echo 'void ray health with probe and marine decoration '.
$ship->get_health()."<br/>";//2
echo "<br/><br/>";

$ship = new brood_lord();
echo 'brood_lord health '.
$ship->get_health()."<br/>";//3
$ship = new probe_decorator(
    new brood_lord()
);
echo 'brood_lord health with probe decoration '.
$ship->get_health()."<br/>";//4
$ship = new marine_decorator(
    new brood_lord()
);
echo 'brood_lord health with marine decoration '.
$ship->get_health()."<br/>";//2
$ship = new probe_decorator(
    new marine_decorator(
        new brood_lord()
    )
);
echo 'brood_lord health with probe and marine decoration '.
$ship->get_health()."<br/>";//3
echo "<br/><br/>";

$ship = new banshee();
echo 'banshee health '.
$ship->get_health()."<br/>";//5
$ship = new probe_decorator(
    new banshee()
);
echo 'banshee health with probe decoration '.
$ship->get_health()."<br/>";//6
$ship = new marine_decorator(
    new banshee()
);
echo 'banshee health with marine decoration '.
$ship->get_health()."<br/>";//4
$ship = new probe_decorator(
    new marine_decorator(
        new banshee()
    )
);
echo 'banshee health with probe and marine decoration '.
$ship->get_health()."<br/>";//5
echo "<br/><br/>";
</pre>
<p>with an output of: </p>
<pre>
void ray health 2
void ray health with probe decoration 3
void ray health with marine decoration 1
void ray health with probe and marine decoration 2

brood_lord health 3
brood_lord health with probe decoration 4
brood_lord health with marine decoration 2
brood_lord health with probe and marine decoration 3

banshee health 5
banshee health with probe decoration 6
banshee health with marine decoration 4
banshee health with probe and marine decoration 5
</pre>
<p>As you can see we were able to do the same thing as the inheritance example without inflexibility, duplication, and an explosion of classes.  And look how easy it is now to add more decorators, even at runtime.</p>
]]></content:encoded>
			<wfw:commentRss>http://discdev.com/2011/09/21/decorator-pattern-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using MySQL Index to speed up the loading of web pages</title>
		<link>http://discdev.com/2011/09/12/using-mysql-index-to-speed-up-the-loading-of-web-pages/</link>
		<comments>http://discdev.com/2011/09/12/using-mysql-index-to-speed-up-the-loading-of-web-pages/#comments</comments>
		<pubDate>Mon, 12 Sep 2011 18:42:13 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Index]]></category>
		<category><![CDATA[MySql]]></category>

		<guid isPermaLink="false">http://discdev.com/?p=929</guid>
		<description><![CDATA[The loading of our client information pages at work has been taking longer and longer over time. We have cached as much as we can to help solve this problem. There is only so much we can cache being that these pages are very dynamic and permission driven. Then we looked into MySQL indexes to [...]]]></description>
			<content:encoded><![CDATA[<iframe src="http://www.facebook.com/plugins/like.php?href=http://discdev.com/2011/09/12/using-mysql-index-to-speed-up-the-loading-of-web-pages/&amp;layout=button_count&amp;show_faces=1&amp;width=450&amp;action=like&amp;colorscheme=light&amp;font=" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:25px"></iframe><p>The loading of our client information pages at work has been taking longer and longer over time.  We have cached as much as we can to help solve this problem.  There is only so much we can cache being that these pages are very dynamic and permission driven.  Then we looked into MySQL indexes to help with some of our larger tables in the database.  One of our problems is that some of our database tables have grown so big that it is taking forever for MySQL to read through them to find the rows we are looking for.<span id="more-929"></span></p>
<p>MySQL Indexes helped with these large tables by indexing the columns that were are using in our WHERE clauses in the SQL SELECT statements.  A table that we added the index to is up to over 600,000 rows.  At the most we are only looking for 52 rows.  We are using a column that is not the primary key in the WHERE clause of the SQL SELECT statement.  So by indexing that column the speed of the SQL calls have been greatly increased. </p>
<p>MySQL Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks. &#8211; <a href="http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html" title="MySQL Index" target="_blank">http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html</a></p>
<p>All MySQL data types can be indexed. Use of indexes on the relevant columns is the best way to improve the performance of SELECT operations.</p>
<p>Just remember that PRIMARY KEY, UNIQUE, FULLTEXT are already indexed.</p>
]]></content:encoded>
			<wfw:commentRss>http://discdev.com/2011/09/12/using-mysql-index-to-speed-up-the-loading-of-web-pages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Refactoring Code for OOP (Object Oriented Programing)</title>
		<link>http://discdev.com/2011/08/26/refactoring-code-for-oop-object-oriented-programing/</link>
		<comments>http://discdev.com/2011/08/26/refactoring-code-for-oop-object-oriented-programing/#comments</comments>
		<pubDate>Fri, 26 Aug 2011 22:56:38 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[codes-in-oop]]></category>
		<category><![CDATA[don-roberts-duplicate-code]]></category>
		<category><![CDATA[how-is-refactoring-in-object-oriented-programming]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[oop-refactoring]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[refactoring-in-oop]]></category>

		<guid isPermaLink="false">http://discdev.com/?p=914</guid>
		<description><![CDATA[Refactoring is the process of taking a running program and adding to its value, not by changing its behavior but by giving it more of these qualities that enable us to continue developing at speed. Refactoring can also be thought of as making changes to code without change the observable behavior of the software. Adding [...]]]></description>
			<content:encoded><![CDATA[<iframe src="http://www.facebook.com/plugins/like.php?href=http://discdev.com/2011/08/26/refactoring-code-for-oop-object-oriented-programing/&amp;layout=button_count&amp;show_faces=1&amp;width=450&amp;action=like&amp;colorscheme=light&amp;font=" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:25px"></iframe><p>Refactoring is the process of taking a running program and adding to its value, not by changing its behavior but by giving it more of these qualities that enable us to continue developing at speed.  Refactoring can also be thought of as making changes to code without change the observable behavior of the software.  Adding functionality and refactoring are two different things.<br />
<span id="more-914"></span></p>
<p>Refactoring can be used to:</p>
<p>Help find bugs.<br />
Reduces bugs.<br />
Helps to develop code more quickly.<br />
Helps improve design.<br />
Helps improve readability by tidying up the code.<br />
Makes the code easier to understand.<br />
Helps with agile development.<br />
Reduces the amount of code overall to get the same job done.<br />
Makes your code more efficient.<br />
Makes your code easier to modify.<br />
Better performance of your software.<br />
Reduces duplicate code.</p>
<blockquote><p>“The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor” &#8211; Don Roberts.</p></blockquote>
<p>Refactoring Improves design. </p>
<blockquote><p>Without a good design, you can progress quickly for a while, but soon the poor design starts to slow you down. You spend time finding and fixing bugs instead of adding new function.</p></blockquote>
<p>Times to refactor are: </p>
<p>After you add function.<br />
When you need to fix a bug.</p>
<p>Things in your code to look out for:</p>
<p><strong>Duplicated Code</strong><br />
If you have duplicate code try to unify it into one place. If the duplicate code is in multiple classes you may have to pull that code out of those classes and make a new class out of that.  Duplicate code is bad because if you have to change that code you will have to do it in multiple places.</p>
<p><strong>Long Methods</strong><br />
Long methods are bad because the longer a procedure is, the more difficult it is to understand.  Try breaking up the method with calls to smaller methods, or taking groups of small methods and putting them into their own class.  Small methods are not a bad thing and are reusable.  Remember to name your small methods so you don&#8217;t have to look at the body of the method to know what the method does.  Conditionals and loops also give signs for extractions. Use Decompose Conditional to deal with conditional expressions. With loops, extract the loop and the code within the loop into its own method. </p>
<p><strong>Large Classes</strong><br />
To me Large Class and Large Method are similar in that you need to break them down.  In order to break down a Class though you have other options like extracting a class into its own class, sub-classes, reduce redundant code.</p>
<p><strong>Long Parameter Lists</strong><br />
In OOP you do not always need to pass every parameter needed because you can always ask objects for them during the routine.  Just pass enough so that the method can get to everything it needs.</p>
<p><strong>Divergent Change</strong><br />
Divergent Change  happened when multiple classes are using another class for something and if that something is changed it might not hold well for all classes.</p>
<p><strong>Shotgun Surgery</strong><br />
Shotgun Surgery  happens when you make a lot of little changes to a lot of different classes.  When you have to make changes that are all over the place, they are hard to find, and easy to miss.  Try pull these changes to one centralized place like a class of its own.  This way from now on you can make changed in one place.</p>
<p><strong>Feature Envy</strong><br />
Feature Envy is when a method seems more interested in a class other that the one it resides in.  Like when your method is invoking 6 or more methods of another object.  This method clearly wants to be somewhere else.  So move this method to the other class.  Sometimes only part of the method suffers from Feature Envy.  In this case just extract that part to the other class.  The fundamental rule of thumb is to put things together that change together.</p>
<p><strong>Data Clumps</strong><br />
Data Clumps are bunches of data that hang around together, usually parameter lists or field lists.  These bunches of data should be made into their own object.  An example could be a order object with a parameter list of form fields.  This list could be broken up into contact, payment, package, ect. </p>
<p><strong>Primitive Obsession</strong><br />
Primitive Obsession is where a primitive(string, int, bool) is used instead of an object.  An example would be were a primitive string is being used for a client instead of a object.  An object would be better.  Another example would be using a sting for a phone number instead of an object.  With an phone object you would be able to format the phone number.</p>
<p><strong>Switch Statements</strong><br />
Switch Statements usually will produce duplication.  Often you find the same switch statements scattered about your program in different places.  If you add a new clause to the switch, you have to find all these switch statements and change them.  Using Polymorphism is the fix here.  <a href="http://discdev.com/2011/08/05/php-strategy-design-pattern/" title="PHP Strategy Design Pattern">Strategy Design Pattern</a> is a useful way of fixing this.</p>
<p><strong>Parallel Inheritance Hierarchies</strong><br />
Parallel Inheritance Hierarchy is when every time you make a subclass of one class, you also have to make a subclass of another.  Make sure that instances of one hierarchy refer to instances of the other.</p>
<p><strong>Lazy Class</strong><br />
Lazy Classes usually are created with downsizing or refactoring of a class till it no longer does anything useful.  Consider removing this class altogether.  If this is a subclass consider collapsing this into its parent class.</p>
<p><strong>Speculative Generality</strong><br />
Speculative Generality is when you have to many hooks and special cases for abilities that you think your code may need someday.  This can result in code that is harder to understand and maintain.</p>
<p><strong>Temporary Field</strong><br />
Temporary Field is when an object has instance variables that are only set in certain circumstances.  This can make the code hard to understand because you expect an object to need all of its variables.  Take these variables and create a class of their own.  Then call for this class if needed.</p>
<p><strong>Message Chains</strong><br />
You see message chains when a client asks one object for another object, which the client thenasks for yet another object, which the client then asks for yet another another object, and so on.  Move the final method up the chain or extract the method to its own class.</p>
<p><strong>Middle Man</strong><br />
Middle Man is when you have an object that that is delegating work to other objects.  Remove the middle man and talk directly to the objects or your can turn the delegation into a subclass.</p>
<p><strong>Inappropriate Intimacy</strong><br />
Inappropriate Intimacy is when two or more classes have common interests.  Pull out the common interest and put it into its own class.</p>
<p><strong>Alternative Classes with Different Interfaces</strong><br />
Alternative Classes with Different Interfaces is when you have two or more classes that are supposed to be doing the same thing but have different method names to do the same thing(Interface).   Rename these methods to match each other(have same interface).</p>
<p><strong>Incomplete Library Class</strong><br />
Incomplete Library Class is when your system has a library class that is incomplete but you want to add to it and have no access to it.  In this case you can use the Foreign method, Create a method in the your foreign library class with an instance of the library class as its first argument.</p>
<p><strong>Data Class</strong><br />
Data Class is a class that has fields, getting and setting methods for the fields, and nothing else.  Data classes are like children. This is nothing more than an array.  They are okay as a starting point, but to participate as a grownup object, they need to take some responsibility.</p>
<p><strong>Refused Bequest</strong><br />
Refused Bequest is a subclass that does not want or need what it is given.  Parent objects should only hold what is in common with all its subclasses.  These methods should be pushed down from the parent to the child who uses it.</p>
<p><strong>Comments</strong><br />
Comments are sometimes there because the code is bad and needs explaining.  A comment should be a place to say why you did something.  If you have a comment to explain what the method does try renaming the method to say this.</p>
<p><strong>Conditionals and Loops</strong><br />
Conditionals and loops also give signs for extractions. Use Decompose Conditional to deal with conditional expressions. With loops, extract the loop and the code within the loop into its own method. </p>
<p>Most of this information I got from reading &#8216;Refactoring: Improving the Design of Existing Code &#8211; By: Martin Fowler; Kent Beck; John Brant; William Opdyke; Don Roberts.  This book is a good read and I recommend it.</p>
]]></content:encoded>
			<wfw:commentRss>http://discdev.com/2011/08/26/refactoring-code-for-oop-object-oriented-programing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a GrooveShark Music Widget on your Website</title>
		<link>http://discdev.com/2011/08/05/creating-a-grooveshark-music-widget-on-your-website/</link>
		<comments>http://discdev.com/2011/08/05/creating-a-grooveshark-music-widget-on-your-website/#comments</comments>
		<pubDate>Fri, 05 Aug 2011 22:45:09 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[create-a-widget-from-grooveshark]]></category>
		<category><![CDATA[custom-groove-shark-widget-themes]]></category>
		<category><![CDATA[custom-widget-for-grooveshark]]></category>
		<category><![CDATA[groove-shark-widget-for-your-website]]></category>
		<category><![CDATA[grooveshark-dev]]></category>
		<category><![CDATA[grooveshark-website-widget]]></category>
		<category><![CDATA[grooveshark-widget-code]]></category>
		<category><![CDATA[grooveshark-widget-for-my-website]]></category>
		<category><![CDATA[grooveshark-widget-settings]]></category>
		<category><![CDATA[music-widget-for-website]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://discdev.com/?p=909</guid>
		<description><![CDATA[I found that you can create a GrooveShark Music Widget on your own website made from one of your playlist on GrooveShark. First thing is to goto GrooveShark and create an account so that your playlist will last. Next is to create a playlist on GrooveShark of songs you would like played on your website. [...]]]></description>
			<content:encoded><![CDATA[<iframe src="http://www.facebook.com/plugins/like.php?href=http://discdev.com/2011/08/05/creating-a-grooveshark-music-widget-on-your-website/&amp;layout=button_count&amp;show_faces=1&amp;width=450&amp;action=like&amp;colorscheme=light&amp;font=" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:25px"></iframe><p>I found that you can create a GrooveShark Music Widget on your own website made from one of your playlist on GrooveShark. First thing is to goto GrooveShark and create an account so that your playlist will last. Next is to create a playlist on GrooveShark of songs you would like played on your website. Once you have your playlist you can right click on the playlist and goto &#8216;share playlist&#8217; then &#8216;Widget&#8217;. A dialog box will pop up with options for your Widget. Customize your GrooveShark Widget. Copy the Embed Code and past it into your site.</p>
<p><span id="more-909"></span></p>
<p><object width="250" height="250" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="wmode" value="window" /><param name="allowScriptAccess" value="always" /><param name="flashvars" value="hostname=cowbell.grooveshark.com&amp;playlistID=31276584&amp;bbg=FFFFFF&amp;bth=FFFFFF&amp;pfg=FFFFFF&amp;lfg=FFFFFF&amp;bt=7A7A7A&amp;pbg=7A7A7A&amp;pfgh=7A7A7A&amp;si=7A7A7A&amp;lbg=7A7A7A&amp;lfgh=7A7A7A&amp;sb=7A7A7A&amp;bfg=D6D6D6&amp;pbgh=D6D6D6&amp;lbgh=D6D6D6&amp;sbh=D6D6D6&amp;p=0" /><param name="src" value="http://grooveshark.com/widget.swf" /><param name="allowscriptaccess" value="always" /><embed width="250" height="250" type="application/x-shockwave-flash" src="http://grooveshark.com/widget.swf" wmode="window" allowScriptAccess="always" flashvars="hostname=cowbell.grooveshark.com&amp;playlistID=31276584&amp;bbg=FFFFFF&amp;bth=FFFFFF&amp;pfg=FFFFFF&amp;lfg=FFFFFF&amp;bt=7A7A7A&amp;pbg=7A7A7A&amp;pfgh=7A7A7A&amp;si=7A7A7A&amp;lbg=7A7A7A&amp;lfgh=7A7A7A&amp;sb=7A7A7A&amp;bfg=D6D6D6&amp;pbgh=D6D6D6&amp;lbgh=D6D6D6&amp;sbh=D6D6D6&amp;p=0" allowscriptaccess="always" /></object></p>
]]></content:encoded>
			<wfw:commentRss>http://discdev.com/2011/08/05/creating-a-grooveshark-music-widget-on-your-website/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP Strategy Design Pattern</title>
		<link>http://discdev.com/2011/08/05/php-strategy-design-pattern/</link>
		<comments>http://discdev.com/2011/08/05/php-strategy-design-pattern/#comments</comments>
		<pubDate>Fri, 05 Aug 2011 22:25:26 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[database-startegy-pattern-php]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[design-pattern-strategy-php]]></category>
		<category><![CDATA[examples-of-strategy-design-pattern-php]]></category>
		<category><![CDATA[php-strategy-design-pattern]]></category>
		<category><![CDATA[php-strategy-entwurfsmuster-abstract]]></category>
		<category><![CDATA[php-strategy-pattern-database]]></category>
		<category><![CDATA[source-code-for-how-to-give-particular-permissions-to-admin-role-in-kohana]]></category>
		<category><![CDATA[Strategy Design Pattern]]></category>
		<category><![CDATA[strategy-pattern-php]]></category>

		<guid isPermaLink="false">http://discdev.com/?p=905</guid>
		<description><![CDATA[PHP Strategy Design Pattern Strategy Design Pattern Is an abstract base class that implements by inheriting classes that can be instantiated into concrete objects. Strategies can be used for deciding what type of image to create(.png or .jpeg) or what type of compression to use(.tar.qz or .zip) when zipping a file, determined by what system [...]]]></description>
			<content:encoded><![CDATA[<iframe src="http://www.facebook.com/plugins/like.php?href=http://discdev.com/2011/08/05/php-strategy-design-pattern/&amp;layout=button_count&amp;show_faces=1&amp;width=450&amp;action=like&amp;colorscheme=light&amp;font=" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:25px"></iframe><p>PHP Strategy Design Pattern</p>
<p>Strategy Design Pattern Is an abstract base class that implements by inheriting classes that can be instantiated into concrete objects.  Strategies can be used for deciding what type of image to create(.png or .jpeg) or what type of compression to use(.tar.qz or .zip) when zipping a file, determined by what system the user is on($_SERVER['HTTP_USER_AGENT']).   Certain methods within a class may be grouped together using another class as their strategy.<br />
<span id="more-905"></span><br />
There are clear examples of the Strategy pattern outside the domain of programming.  If I need to get to the Disc Golf Course from my house, I can choose among several strategies: I can walk, ride a bike, drive my car, or get a ride from a friend.  Each strategy has the same result, but uses resources differently, and the choice of the strategy depends on the expense, time, the availability of a particular resource (like owning a bike), and the convenience of each method.  A good strategy on one day may be a poor one the next, so the choice of strategy has to be made dynamically.</p>
<p>Here are the files that go along with the following problem: <a href='http://discdev.com/wp-content/uploads/2011/08/Strategy-Pattern.tar.gz'>Strategy Pattern.tar</a></p>
<p>The Problem</p>
<p>I am a Web Developer with the job of migrating our internal administration back end from our old internal built framework and database to a new internal administration back end built using the open source Framework Kohana and a new database to go with the Kohana Framework.  The problem I am running into is that we have other scripts outside of these frameworks that make calls to the administration database.  So I need to have a way to put in a switch for these outside scripts to be able to switch databases so that at the time of the big switch from the old database to the new one I can just change one constant and the outside scripts will change databases calls.  This is where the strategy pattern comes into play.  I will have two strategies, the old admin strategy and the new admin strategy.  </p>
<p>To start off with I will define a constant at the beginning of the script(s) that will hold the type of database strategy to be in use, either &#8216;old&#8217; or &#8216;new&#8217;.  This could have been defined in other ways like using the date of the big move as the defining factor of what database strategy to use, but here I am using the constant.  On the day of the big move I will change the constant.  I will call the constant ADMIN_STRATEGY.    ADMIN_STRATEGY will either be set to &#8216;old&#8217; or &#8216;new&#8217;.</p>
<p>Next I will create an abstract class called adminversion. This class will have a factory that will create the concrete strategy object out of one of the two strategy classes.  The two strategy classes are adminversionold and adminversionnew.  The Concrete class that will be instantiated will be determined by the ADMIN_STRATEGY constant.  The two main methods that the each strategy will need is get_sql($call) and get_admin_database().  The get_sql($call) method will return the SQL statement that is used for the $call type.  $call types can be things like get_all_client_ids, get_client_package, or get_client_address.  So the SQL statements for the old admin will be different from the new admin.  The get_admin_database() method will return an mysqli object that corresponds to the database for that strategy.</p>
<p>So lets take a closer look at the internals of the abstract class adminversion.  First is the public static function factory($version) &#8211; (factory strategy).  This function will return a concrete object that is determined by the $version that is passed.  $version will either be &#8216;old&#8217; or &#8216;new&#8217; as determined by the constant ADMIN_VERSION.  So since ADMIN_VERSION is set to &#8216;old&#8217; the concrete object that will be instantiated will be adminversionold.  As you can see all I did here is concatenate &#8216;old&#8217; onto the end of the string &#8216;adminversion&#8217; to come up with the string adminversionold ($class = &#8216;adminversion&#8217;.$version;).  Then I just returned the instantiated class as a concrete object (return new $class;). </p>
<p>Now lets take a closer look at the adminversionold and adminversionnew classes (strategies) .  They will both have a member property of $sqls that is an array of SQL calls.  These SQL calls are obtained through the adminversion get_sql($call) method.  These two classes will both also have a public function get_admin_database() that will use the db multiton class to return a mysqli object associated with the admin version.</p>
]]></content:encoded>
			<wfw:commentRss>http://discdev.com/2011/08/05/php-strategy-design-pattern/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Factory Design Pattern for PHP</title>
		<link>http://discdev.com/2011/04/27/factory-design-pattern-for-php/</link>
		<comments>http://discdev.com/2011/04/27/factory-design-pattern-for-php/#comments</comments>
		<pubDate>Wed, 27 Apr 2011 22:14:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[design-pattern-php-include]]></category>
		<category><![CDATA[Factory Design Pattern]]></category>
		<category><![CDATA[factory-design-pattern-in-php]]></category>
		<category><![CDATA[Gang of Four]]></category>
		<category><![CDATA[Object]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php-design-pattern-factory]]></category>
		<category><![CDATA[php-factory-design-pattern-framework]]></category>
		<category><![CDATA[Search Engine]]></category>

		<guid isPermaLink="false">http://discdev.com/?p=893</guid>
		<description><![CDATA[The factory design pattern uses a static method inside a factory class that receives some input and according to that input decides what class instance to create as a concrete object. This solves the problem of when you do not know the kind of object that will be needed till run time. Here is the [...]]]></description>
			<content:encoded><![CDATA[<iframe src="http://www.facebook.com/plugins/like.php?href=http://discdev.com/2011/04/27/factory-design-pattern-for-php/&amp;layout=button_count&amp;show_faces=1&amp;width=450&amp;action=like&amp;colorscheme=light&amp;font=" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:25px"></iframe><p>The factory design pattern uses a static method inside a factory class that receives some input and according to that input decides what class instance to create as a concrete object.  This solves the problem of when you do not know the kind of object that will be needed till run time.<span id="more-893"></span> </p>
<p>Here is the situation.  I have a form that you can enter a key phrase and a search engine and then submit.  What is returned is the how the key phrase ranked on a particular search engine.  So I will have a concrete class for each search engine that will return the rank for the key phrase.  I will not know till run time what search engine object to instantiate.  In order to solve this problem I will use a search engine factory class that will instantiate the search engine object for me at run time.  The search engine factory class will have a static method for instantiating the concrete search engine class.  You can download the following file <a href='http://discdev.com/wp-content/uploads/2011/04/engine-example.tar.gz'>engine example.tar</a>.</p>
<p>index.php:</p>
<pre class="brush:php">
<?php
/** @author Phillip Brown <discdev.com> **/

echo "Keyword Analysis Example<br/><br/>";

include('search_engine.php');

if(isset($_POST['key_phrase'])) {
	$search_engine = search_engine::factory($_POST['engine']);
	echo 'Rank: '.
		$search_engine->get_rank($_POST['key_phrase']).
		"<br/>";
?>
	<a href="index.php">restart</a>
<?php } else { ?>
<form method="post">
	Key Phrase:
<input type="text" name="key_phrase"/>
<select name="engine">
<option>Google</option>
<option>Bing</option>
<option>Yahoo</option>
</select>
<input type="submit"/>
</form>

<?php } ?>
</pre>
<p>search_engine.php:</p>
<pre class="brush:php">
<?php
/** @author Phillip Brown <discdev.com> **/
include('html.php');
include('google_search_engine.php');
include('bing_search_engine.php');
include('yahoo_search_engine.php');

abstract class search_engine {

    public static function factory($engine = false) {
        if($engine === false) {
            $engine = 'Google';
        }
        //still need to check for driver
        $engine = $engine.'_search_engine';
        return new $engine;
    }

    abstract public function get_rank($keyphrase);

}
?>
</pre>
<p>google_search_engine.php:</p>
<pre class="brush:php">
<?php
/** @author Phillip Brown <discdev.com> **/
class google_search_engine extends search_engine {

    public function get_rank($keyphrase) {
        $url = $this->get_url(urlencode($keyphrase));
        $rank = $this->parse(html::fetch($url));
        return $rank;
    }

    private function get_url($keyphrase) {
        return "http://www.google.com/search?source=ig&#038;hl=en&#038;rlz=&#038;q=$keyphrase&#038;btnG=Google+Search";
    }

    private function parse($html) {
        if(preg_match('/About ([0-9,]+) results/', $html, $extract)) {
            return str_replace(',', '', $extract[1]);
        } else {
            return 0;
        }
    }

}
?>
</pre>
<p>yahoo_search_engine.php:</p>
<pre class="brush:php">
<?php
/** @author Phillip Brown <discdev.com> **/
class yahoo_search_engine extends search_engine {

    public function get_rank($keyphrase) {
        $url = $this->get_url(urlencode($keyphrase));
        $rank = $this->parse(html::fetch($url));
        return $rank;
    }

    private function get_url($keyphrase) {
      	return "http://search.yahoo.com/search;_ylt=A0oGdVfcU2RNhQABQqBXNyoA;_ylc=X1MDMjc2NjY3OQRfcgMyBGFvAzAEZnIDeWZwLXQtNTAxBGhvc3RwdmlkA3FRVURuMG9HZFRBSS5xTWNTS0lnWUF5TkdPcHl5VTFrVTl3QUJ6aDcEbl9ncHMDOQRuX3ZwcwMxMARvcmlnaW4Dc3JwBHF1ZXJ5A3JlYWwgZXN0YXRlBHNhbwMxBHZ0ZXN0aWQD?p=$keyphrase&#038;fr2=sb-top&#038;fr=yfp-t-501";
    }

    private function parse($html) {
        if(preg_match('/id="resultCount">([0-9,]+)/', $html, $extract)) {
            return str_replace(',', '', $extract[1]);
        } else {
            return 0;
        }
    }

}
?>
</pre>
<p>bing_search_engine.php:</p>
<pre class="brush:php">
<?php
/** @author Phillip Brown <discdev.com> **/
class bing_search_engine extends search_engine {

    public function get_rank($keyphrase) {
        $url = $this->get_url(urlencode($keyphrase));
        $rank = $this->parse(html::fetch($url));
        return $rank;
    }

    private function get_url($keyphrase) {
        return "http://www.bing.com/search?q=$keyphrase&#038;FORM=MSNH";
    }

    private function parse($html) {
        if(preg_match('/1-[0-9]+ of ([0-9,]+)/', $html, $extract)) {
            return str_replace(',', '', $extract[1]);
        } else {
            return 0;
        }
    }

}
?>
</pre>
<p>html.php:</p>
<pre class="brush:php">
<?php
/** @author Phillip Brown <discdev.com> **/
class html {
    /**
     * retrieve the html from a remote website
     * @param $url the url to fetch the html from
     */
    public static function fetch($url) {
        $curl_options = array();
        $curl_options[CURLOPT_RETURNTRANSFER] = true;;
        $curl_options[CURLOPT_USERAGENT] =
        	'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9';
        $ch = curl_init($url);
        curl_setopt_array($ch, $curl_options);
        return curl_exec($ch);
    }
}
?>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://discdev.com/2011/04/27/factory-design-pattern-for-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multiton Design Pattern for PHP</title>
		<link>http://discdev.com/2011/04/25/multiton-design-pattern-for-php/</link>
		<comments>http://discdev.com/2011/04/25/multiton-design-pattern-for-php/#comments</comments>
		<pubDate>Mon, 25 Apr 2011 18:31:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Gang of Four]]></category>
		<category><![CDATA[multi-ton-design-pattern]]></category>
		<category><![CDATA[multiple-db-connection-class-php-pattern]]></category>
		<category><![CDATA[Multiton Design Pattern]]></category>
		<category><![CDATA[multiton-design-pattern-example]]></category>
		<category><![CDATA[multiton-how-to-use]]></category>
		<category><![CDATA[multiton-pattern]]></category>
		<category><![CDATA[multiton-pattern-php]]></category>
		<category><![CDATA[multiton-php]]></category>
		<category><![CDATA[Object]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php-multi-ton]]></category>
		<category><![CDATA[php-multi-ton-design-patterns]]></category>
		<category><![CDATA[php-multiton]]></category>
		<category><![CDATA[php-multiton-pattern]]></category>
		<category><![CDATA[php-pattern-multiton]]></category>
		<category><![CDATA[Singleton Design Pattern]]></category>

		<guid isPermaLink="false">http://discdev.com/?p=889</guid>
		<description><![CDATA[The Multiton Design Pattern is a variance on the Singleton Design Pattern. The Multiton Pattern expands on the Singleton concept to manage a associative array of named instances as key-value pairs or a Registry of singletons. The multiton pattern ensures a single instance per key. The example I am going to use here is a [...]]]></description>
			<content:encoded><![CDATA[<iframe src="http://www.facebook.com/plugins/like.php?href=http://discdev.com/2011/04/25/multiton-design-pattern-for-php/&amp;layout=button_count&amp;show_faces=1&amp;width=450&amp;action=like&amp;colorscheme=light&amp;font=" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:25px"></iframe><p>The Multiton Design Pattern is a variance on the Singleton Design Pattern.  The Multiton Pattern expands on the Singleton concept to manage a associative array of named instances as key-value pairs or a Registry of singletons.  The multiton pattern ensures a single instance per key.<span id="more-889"></span></p>
<p>The example I am going to use here is a variance of the database singleton design pattern I used in my blog on the &#8216;<a href="http://discdev.com/2011/04/21/singleton-design-pattern-for-php/">Singleton Design Pattern for PHP</a>&#8216;.  In that example I used the singleton design pattern to create a instance of an database singleton class that has a single connection to the database.  The every time from then on you use the same instance for calls to the database anywhere in your application.</p>
<p>Now all the sudden your application has a need for multiple databases but you still want to use the singleton design pattern.  Instead of creating a singleton class for each database I will create a variance of the database singleton design pattern that will create a key-value pair for each database that the application will be using.  For each database key I will be using a concatenation of the host name, user name, and database name.  This will make each key unique to the database.  The first database will be an administration database for things like clients and employees.   The second database will be a sales database for products and costs.  So one of the multiton keys will be for the administration database and the other key will be for the sales database.</p>
<p>Index.php:</p>
<pre class="brush:php">
<?php
/** @author Phillip Brown <discdev.com> **/

echo "Multiton db object Example<br/><br/>";

include('db.php');

// Lets say here for examples sake that we
// do the following code for a list of clients
// in the client class.
echo "Here is the list of clients<br/><br/>";
$db_admin_one = db::get_instance(
	'127.0.0.1',
	'user',
	'pass',
	'admin_db'
);
$sql = "
	SELECT
		`first_name`,
		`last_name`
	FROM
		`clients`
";
$result = $db_admin_one->query($sql);
while($row = $result->fetch_assoc()) {
	echo $row['first_name'].
	' '.
	$row['last_name'].
	"<br/>";
}

// Then here lets say we are in the employee
// class and we dothe following code to get
// a list of employees.
echo "<br/><br/>";
echo "Here is the list of employees<br/><br/>";
$db_admin_two = db::get_instance(
	'127.0.0.1',
	'user',
	'pass',
	'admin_db'
);
echo "db_admin_two instance created<br/><br/>";
$sql = "
	SELECT
		`first_name`,
		`last_name`
	FROM
		`employees`
";
$result = $db_admin_two->query($sql);
while($row = $result->fetch_assoc()) {
	echo $row['first_name'].
	' '.
	$row['last_name'].
	"<br/>";
}

// HERE AT THIS POINT WE WILL BE USING A
// DIFFERENT DATABASE AND THE SAME
// MULTITON CLASS

// Lets say here for examples sake that we
// do the following code for a list of products
// in the procuct class.
echo "Here is the list of products<br/><br/>";
$db_sales_one = db::get_instance(
	'127.0.0.1',
	'user',
	'pass',
	'sales_db'
);
$sql = "
	SELECT
		`name`
	FROM
		`product`
";
$result = $db_sales_one->query($sql);
while($row = $result->fetch_assoc()) {
	echo $row['name'].
	"<br/>";
}

// Then here lets say we are in the cost
// class and we do the following code to get
// a list of costs.
echo "<br/><br/>";
echo "Here is the list of costs<br/><br/>";
$db_sales_two = db::get_instance(
	'127.0.0.1',
	'user',
	'pass',
	'sales_db'
);
echo "db_sales_two instance created<br/><br/>";
$sql = "
	SELECT
		`amount`
	FROM
		`cost`
";
$result = $db_sales_two->query($sql);
while($row = $result->fetch_assoc()) {
	echo $row['amount'].
	"<br/>";
}
?>
</pre>
<p>db.php:</p>
<pre class="brush:php">
<?php
/** @author Phillip Brown <discdev.com> **/

class db {

	private static $instance = array();

	private function __construct() { }

    public static function get_instance(
    	$host,
    	$username,
    	$password,
    	$database)
    {
    	if(empty(self::$instance[$host.$username.$database])) {
        	self::$instance[$host.$username.$database] = new mysqli(
        		$host,
        		$username,
        		$password,
        		$database
        	);
     	}
      	return self::$instance[$host.$username.$database];
   	}

}
?>
</pre>
<p>Output:</p>
<pre>
Here is the list of clients
john doe
frank tank
sally may

Here is the list of employees
kim green
jayme mcmillian
jay walsh

Here is the list of products
cup
plate
bowl

here is the list of costs
$10.00
$32.00
$6.00
</pre>
]]></content:encoded>
			<wfw:commentRss>http://discdev.com/2011/04/25/multiton-design-pattern-for-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New Disc Golf Course in Henderson Nevada</title>
		<link>http://discdev.com/2011/04/22/new-disc-golf-course-in-henderson-nevada/</link>
		<comments>http://discdev.com/2011/04/22/new-disc-golf-course-in-henderson-nevada/#comments</comments>
		<pubDate>Fri, 22 Apr 2011 18:36:41 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Disc Golf]]></category>
		<category><![CDATA[disc-golf-course-henderson-nv]]></category>
		<category><![CDATA[disc-golf-henderson-nv]]></category>
		<category><![CDATA[disc-golf-henderson-nv-2012]]></category>
		<category><![CDATA[disc-golf-pattern]]></category>
		<category><![CDATA[frisbee-golf-courses-henderson-nb]]></category>
		<category><![CDATA[frisbee-golf-henderson-nevada]]></category>
		<category><![CDATA[frisbee-golf-henderson-nv]]></category>
		<category><![CDATA[frisbee-golf-in-henderson-nv]]></category>
		<category><![CDATA[henderson-disc-golf-course]]></category>
		<category><![CDATA[henderson-frisbee-golf]]></category>
		<category><![CDATA[how-to-find-out-if-your-rental-home-is-in-foreclosure-clark-county-nevada]]></category>
		<category><![CDATA[nevada-disc-golf]]></category>

		<guid isPermaLink="false">http://discdev.com/?p=879</guid>
		<description><![CDATA[I heard today that there is a new Disc Golf Course in Henderson Nevada. It is located at Horizon Ridge and Paseo Verde, east of Gibson under the power lines. The name of the Course is either &#8216;Paseo Verde Trailhead&#8217; or &#8216;Amargosa trail&#8217;. Rob Toltzman said “It&#8217;s on the east side of Paseo Verde, just [...]]]></description>
			<content:encoded><![CDATA[<iframe src="http://www.facebook.com/plugins/like.php?href=http://discdev.com/2011/04/22/new-disc-golf-course-in-henderson-nevada/&amp;layout=button_count&amp;show_faces=1&amp;width=450&amp;action=like&amp;colorscheme=light&amp;font=" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:25px"></iframe><p>I heard today that there is a new Disc Golf Course in Henderson Nevada.  It is located at Horizon Ridge and Paseo Verde, east of Gibson under the power lines.  The name of the Course is either  &#8216;Paseo Verde Trailhead&#8217; or &#8216;Amargosa trail&#8217;.<span id="more-879"></span></p>
<p>Rob Toltzman said “It&#8217;s on the east side of Paseo Verde, just north of Horizon Ridge. Approx 1/2 mile east of Gibson. Some elevation changes, looks like Mach 5 baskets with dirt box tee pads.”</p>
<p>Patrick Kjenstad said “small family style course. holes 1-3 need to be redone to be a decent course. better than nothing tho.”</p>
<p>This new course is close to Las vegas Nevada, Boulder City Nevada.</p>
<p>Here are some better directions from Patrick Kjenstad: horizon ridge and paseo verde. 215 to gibson. south on gibson. east on horizon ridge about a 1/2 mile or so. left on paseo verde. its on the right all the way to end of street.</p>
]]></content:encoded>
			<wfw:commentRss>http://discdev.com/2011/04/22/new-disc-golf-course-in-henderson-nevada/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

