<?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>Views From The Hill &#187; How-To</title>
	<atom:link href="http://dustint.com/archives/category/how-to/feed" rel="self" type="application/rss+xml" />
	<link>http://dustint.com</link>
	<description>Tales Of A (Former) SFU Computing Scientist</description>
	<lastBuildDate>Thu, 17 Jun 2010 20:14:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Enable Xdebug HTML Output</title>
		<link>http://dustint.com/archives/234</link>
		<comments>http://dustint.com/archives/234#comments</comments>
		<pubDate>Fri, 28 May 2010 02:28:31 +0000</pubDate>
		<dc:creator>Dustin</dc:creator>
				<category><![CDATA[How-To]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://dustint.com/?p=234</guid>
		<description><![CDATA[I recently updated to Ubuntu 10.04 which includes PHP-5.3 by default. Ever since that upgrade I&#8217;ve had trouble with Xdebug not displaying HTML in its output: instead it would output human-readable text which becomes quite unreadable when rendered in the browser without &#60;pre&#62; tags. Turns out when PHP was upgraded, the php.ini file was replaced, [...]]]></description>
			<content:encoded><![CDATA[<p>I recently updated to Ubuntu 10.04 which includes PHP-5.3 by default. Ever since that upgrade I&#8217;ve had trouble with Xdebug not displaying HTML in its output: instead it would output human-readable text which becomes quite <em>unreadable</em> when rendered in the browser without  &lt;pre&gt; tags.</p>
<p>Turns out when PHP was upgraded, the php.ini file was replaced, and in the new version, it has the production value for <strong>html_errors</strong> which is Off. Once I set <strong>html_errors=On</strong> in /etc/php5/apache, colourful HTML-formatted output was producted by Xdebug.</p>
<p>For the Curious reader, I&#8217;m using the following xdebug configuration file, which I&#8217;ve located in <em>/etc/php5/conf.d/xdebug.ini</em> to prevent any php.ini changes from overwriting my Xdebug directives. Please note that this is a slightly modified version of the default xdebug configuration included in <a href="http://www.wampserver.com/">wamp</a>, which I find to be quite nice:</p>

<div class="wp_syntax"><div class="code"><pre class="ini" style="font-family:monospace;"><span style="color: #000099;">zend_extension</span><span style="color: #000066; font-weight:bold;">=</span><span style="color: #933;">&quot;/usr/lib/php5/20090626/xdebug.so&quot;</span>
xdebug.remote_enable<span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">1</span>
xdebug.remote_host<span style="color: #000066; font-weight:bold;">=</span><span style="color: #933;">&quot;127.0.0.1&quot;</span>
xdebug.remote_port<span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">9000</span>
xdebug.remote_handler<span style="color: #000066; font-weight:bold;">=</span><span style="color: #933;">&quot;dbgp&quot;</span>
xdebug.remote_mode<span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">req</span>
xdebug.profiler_enable<span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">1</span>
xdebug.profiler_output_dir<span style="color: #000066; font-weight:bold;">=</span><span style="color: #933;">&quot;/tmp/xprofile/&quot;</span>
xdebug.collect_params<span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">On</span>
xdebug.show_local_vars<span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">On</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://dustint.com/archives/234/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Build an API for any website with Web-Scraping</title>
		<link>http://dustint.com/archives/184</link>
		<comments>http://dustint.com/archives/184#comments</comments>
		<pubDate>Sun, 16 May 2010 07:00:21 +0000</pubDate>
		<dc:creator>Dustin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Screen Scraping]]></category>
		<category><![CDATA[Web Scraping]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://dustint.com/?p=184</guid>
		<description><![CDATA[There are a lot of web-sites out there, with a lot of data on them. Sometimes you are building a killer web-app and you just have to have some data off a certain site. The problem is, that particular site doesn&#8217;t have an API that you can just plug into! Never fear, using some simple [...]]]></description>
			<content:encoded><![CDATA[<p>There are a lot of web-sites out there, with a lot of data on them. Sometimes you are building a killer web-app and you just have to have some data off a certain site. The problem is, that particular site doesn&#8217;t have an API that you can just plug into! Never fear, using some simple tools, combined with the Zend Framework you can create your own web-scraping (screen-scraping) API in no time.</p>
<p>Before I continue, I should mention that, not only is it impolite, but quite possibly illegal to take the content of a third party site without the owners permission or knowledge.</p>
<p>To accomplish our task we need some open-source tools:</p>
<ul>
<li><a title="Zend Framework" href="http://framework.zend.com">Zend Framework</a> (Required)</li>
<li><a href="http://quixapp.com/">Quix</a> (Recommended)</li>
<li><a title="Dojo Toolkit" href="http://www.dojotoolkit.org/">Dojo Toolkit</a> (Recommended)</li>
</ul>
<p>Our basic strategy is this:</p>
<ol>
<li> Find a target page with some cool content</li>
<li> Find the CSS Selector (or X-path) of the element we want to scrape</li>
<li> Verify the selector using Dojo</li>
<li> Build a Zend_Service object to fetch the cool content to PHP</li>
</ol>
<h2>Step 1: Finding the cool page</h2>
<p>Say I am a developer and I really want to get the outward facing IP of the machine that my PHP script is running on. If there is a router or proxy in between my machine and the Internet, this can be non trivial. As a solution I decide to use the service <a href="http://www.whatismyip.com/">http://www.whatismyip.com/</a></p>
<h2>Step 2: Finding the CSS3 Selector for the element</h2>
<p>Its pretty obvious which element we want to get the selector for. If you are feeling clever you can simply read the code or use a DOM inspector to figure out what the query is on your own. However, selectorgaget.com provides a cool tool that will allow you to point and click to determine the appropraite selector. You can get a bookmarklet directly from their site, or you can get the much more powerful Quix bookmarklet which includes the selectorgaget and a bunch of other cool tools.</p>
<p>If you decided on Quix (I know I did), click on the bookmarklet and enter &#8220;sg&#8221; in the command box. The selectorgaget should load up and as you move your mouse around the screen it should highlight different DOM nodes. We want the top one, so click on the text &#8220;Your IP&#8230;&#8221; and, checking out the path, we see that it is a rather boring h1.</p>
<h2>Step 3: Validation via Dojo</h2>
<p>I like to validate the path before taking it over to Zend. I use a Dojo and firebug lite bookmarklet which injects a debugging version of dojo into any page via the AOL CDN. To add this bookmarket drag <a  href="javascript:(function(){%20var%20d=document;%20var%20h=d.getElementsByTagName('HEAD')[0];%20var%20s=d.createElement('script');%20s.type='text/javascript';%20s.src='http://o.aolcdn.com/dojo/1.4.0/dojo/dojo.xd.js.uncompressed.js';%20h.appendChild(s);%20})()">Inject Dojo</a> into your bookmarks toolbar. In the debugging console that pops up, enter dojo.query(&#8216;h1&#8242;); and you should see the h1 DOM element being returned.</p>
<h2>Step 4: Moving it all to PHP</h2>
<p>Now that we have successfully found our CSS3 selector path, we can move over to PHP and come up with a new Zend_Service component. Our approach will be to extend Zend_Service_Abstract, and implement some custom methods to preform the screen scrape.</p>
<p>The finished class looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> WhatsMyIpService <span style="color: #000000; font-weight: bold;">extends</span> Zend_Service_Abstract
<span style="color: #009900;">&#123;</span>
	<span style="color: #009933; font-style: italic;">/**
	 * The service endpoint.
	 * This is where Zend_Http_Client will navigate
	 * to fill service requests
	 * @var string
	 */</span>
	protected <span style="color: #000088;">$_endpoint</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'http://whatismyip.com'</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * handle to the client
	 * @var Zend_Http_Client
	 */</span>
	protected <span style="color: #000088;">$_client</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_client <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #004000;">getHttpClient</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Method to get the external IP of the computer / server
	 * script is running on
	 * @return string
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> getMyIp<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">//reset the client parameters, set the URL to whatismyip.com</span>
		<span style="color: #666666; font-style: italic;">//and actually preform the request</span>
		<span style="color: #000088;">$result</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_client
			<span style="color: #339933;">-&gt;</span><span style="color: #004000;">resetParameters</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
			<span style="color: #339933;">-&gt;</span><span style="color: #004000;">setUri</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_endpoint<span style="color: #009900;">&#41;</span>
			<span style="color: #339933;">-&gt;</span><span style="color: #004000;">request</span><span style="color: #009900;">&#40;</span>Zend_Http_Client<span style="color: #339933;">::</span><span style="color: #004000;">GET</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">//check to make sure that the result isnt a HTTP error</span>
		<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isError</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			throw <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Client returned error: '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$result</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		try<span style="color: #009900;">&#123;</span>
			<span style="color: #666666; font-style: italic;">//setup the query object with the result body (HTML page)</span>
			<span style="color: #000088;">$query</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Zend_Dom_Query<span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getBody</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #000088;">$domCollection</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$query</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'h1'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>catch<span style="color: #009900;">&#40;</span>Zend_Dom_Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			throw <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Error Loading Document: '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">//check to make sure the query return a result</span>
		<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$domCollection</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			throw <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Cannot find DOM Element'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">//get the titlestring from the nodevalue</span>
		<span style="color: #000088;">$titleString</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span> <span style="color: #000088;">$domCollection</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">current</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">nodeValue</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">//now we should have the content of h1 stored in the titleString</span>
		<span style="color: #666666; font-style: italic;">//it should read something like &quot;Your IP Address Is: xxx.xxx.xxx.xxx&quot;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">//Now we will parse out the IP address using regular expressions</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'/([\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3})/'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$titleString</span><span style="color: #339933;">,</span> <span style="color: #000088;">$matches</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #000088;">$matches</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #b1b100;">else</span><span style="color: #009900;">&#123;</span>
			throw <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Unable to parse IP from page'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I hope that the script is sufficiently commented, but to summarize:</p>
<p>In the constructor, we get an local instance of a Zend_Http_Client object. Clone() is used to prevent any other Zend_Service objects from polluting our client with their own requests.</p>
<p>In the getMyIp() method, we first setup and preform the request (using the fluid interface provided by Zend_Http_Client). Notice how we reset the parameters: In this case its not actually necessary as we aren&#8217;t passing any parameters, but it is good habit to get into in case in the future we expand this class to include GET or POST parameter passing.  </p>
<p>Next, we examine what the HTTP client has passed back to us. Hopefully, if nothing has gone wrong, it is a HTML string representation of the page at whatismyip.com. Some basic checks are preformed to ensure that no HTTP errors have occurred, and then we instantiate a Zend_Dom_Query object which provides both CSS  and Xpath selectors.</p>
<p>Finally, after running the CSS selector query, we check to ensure we got a DOM element back, get its value and parse out the IP using Regular expressions. Its pretty impressive what can be done in <70 lines of code with the Zend Framework.</p>
<p>To run this class, we could create a directory structure as follows:<br />
library <- Includes Zend framework<br />
WhatsMyIpService.php <- The above class<br />
getIp.php <- php file including the following:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">set_include_path</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">implode</span><span style="color: #009900;">&#40;</span>PATH_SEPARATOR<span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #990000;">realpath</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">dirname</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">__FILE__</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'/library'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #990000;">get_include_path</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/** Zend_Loader_Autoload **/</span>
<span style="color: #b1b100;">require_once</span> <span style="color: #0000ff;">'Zend/Loader/Autoloader.php'</span><span style="color: #339933;">;</span>
Zend_Loader_Autoloader<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setFallbackAutoloader</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$service</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> WhatsMyIpService<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$service</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getMyIp</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The first couple of lines gets the library on the include path, the second block sets up autoloading so we don&#8217;t have to manually include files, and the final lines instantiates the class and calls the method.</p>
]]></content:encoded>
			<wfw:commentRss>http://dustint.com/archives/184/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Greasemonkey And Dojo Integration Redux</title>
		<link>http://dustint.com/archives/206</link>
		<comments>http://dustint.com/archives/206#comments</comments>
		<pubDate>Sun, 02 May 2010 02:49:16 +0000</pubDate>
		<dc:creator>Dustin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[Greasemonkey]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://dustint.com/?p=206</guid>
		<description><![CDATA[Back in 2007 I wrote a post on how to integrate Dojo with Greasemonkey. Since then, Greasemonkey has been re-written to include security and bug fixes which has broken my demo code. The problem is that the new security model doesn&#8217;t return an instance to the newly created dijit.Dialog when the constructor is called. The [...]]]></description>
			<content:encoded><![CDATA[<p>Back in 2007 I wrote a post on how to integrate Dojo with Greasemonkey.<br />
Since then, Greasemonkey has been re-written to<a href="http://commons.oreilly.com/wiki/index.php/Greasemonkey_Hacks/Getting_Started#Avoid_Common_Pitfalls"> include security and bug fixes</a> which has broken my demo code. The problem is that the new security model doesn&#8217;t return an instance to the newly created dijit.Dialog when the constructor is called. The work-around is to set the ID of the dialog, and then call dijit.byId() to get a handle to it.</p>
<p>Of course, this is going to pose problems when creating non-dijit objects, as they will all be created on the page-level scope. The work-around is likely constructing clever eval() strings, and then accessing the objects using unsafeWindow. If anyone comes up with a more elegant solution, let me know about it in the comments.</p>
<p>The following can be used to overwrite the <a href="http://dustint.com/archives/4">previous version of the user-script</a>, restoring the broken functionality as well as making use of some of the newly introduced Dojo features.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// ==UserScript==</span>
<span style="color: #006600; font-style: italic;">// @name           Dojo Integration Test</span>
<span style="color: #006600; font-style: italic;">// @namespace      test</span>
<span style="color: #006600; font-style: italic;">// @description    Proof Of Concept To Integrate Dojo And Greasemonkey</span>
<span style="color: #006600; font-style: italic;">// @include        *</span>
<span style="color: #006600; font-style: italic;">// ==/UserScript==</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> startup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	dojo <span style="color: #339933;">=</span> unsafeWindow<span style="color: #009900;">&#91;</span><span style="color: #3366CC;">&quot;dojo&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	dijit <span style="color: #339933;">=</span> unsafeWindow<span style="color: #009900;">&#91;</span><span style="color: #3366CC;">&quot;dijit&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
	dojo.<span style="color: #660066;">addClass</span><span style="color: #009900;">&#40;</span>dojo.<span style="color: #660066;">body</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'tundra'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	dojo.<span style="color: #660066;">require</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;dijit.Dialog&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">//Don't do anything until &quot;Dijit.Dialog&quot; has been loaded</span>
	dojo.<span style="color: #660066;">addOnLoad</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #006600; font-style: italic;">//Actually Create The Dialog</span>
		<span style="color: #003366; font-weight: bold;">new</span> dijit.<span style="color: #660066;">Dialog</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
			id<span style="color: #339933;">:</span> <span style="color: #3366CC;">'test'</span><span style="color: #339933;">,</span>
			title<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Dojo Integration Test&quot;</span><span style="color: #339933;">,</span>
			content<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Dojo lives... In Greasemonkey'</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		dijit.<span style="color: #660066;">byId</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'test'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">show</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//include flags to djConfig to tell dojo its being used after its been loaded</span>
unsafeWindow.<span style="color: #660066;">djConfig</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
	afterOnLoad<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">,</span>
	addOnLoad<span style="color: #339933;">:</span> startup
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//Include Dojo from the AOL CDN</span>
<span style="color: #003366; font-weight: bold;">var</span> script <span style="color: #339933;">=</span> document.<span style="color: #660066;">createElement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'script'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
script.<span style="color: #660066;">src</span><span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;http://o.aolcdn.com/dojo/1.4/dojo/dojo.xd.js.uncompressed.js&quot;</span><span style="color: #339933;">;</span>
document.<span style="color: #660066;">getElementsByTagName</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'head'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">appendChild</span><span style="color: #009900;">&#40;</span>script<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//Include the Tundra Theme CSS file</span>
<span style="color: #003366; font-weight: bold;">var</span> link <span style="color: #339933;">=</span> document.<span style="color: #660066;">createElement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'link'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
link.<span style="color: #660066;">rel</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;stylesheet&quot;</span><span style="color: #339933;">;</span>
link.<span style="color: #660066;">type</span><span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;text/css&quot;</span><span style="color: #339933;">;</span>
link.<span style="color: #660066;">href</span><span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;http://o.aolcdn.com/dojo/1.4/dijit/themes/tundra/tundra.css&quot;</span><span style="color: #339933;">;</span>
document.<span style="color: #660066;">getElementsByTagName</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'head'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">appendChild</span><span style="color: #009900;">&#40;</span>link<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://dustint.com/archives/206/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaScript Sudoku Solver</title>
		<link>http://dustint.com/archives/190</link>
		<comments>http://dustint.com/archives/190#comments</comments>
		<pubDate>Thu, 25 Mar 2010 21:04:04 +0000</pubDate>
		<dc:creator>Dustin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[Artifical Intelligence]]></category>
		<category><![CDATA[Constraint Satisfaction]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Sudoku]]></category>

		<guid isPermaLink="false">http://dustint.com/?p=190</guid>
		<description><![CDATA[In Computing science artificial intelligence terms, the game of Sudoku is a constraint satisfaction problem. Constraint satisfaction problems are nice in the regard that there are some very nice heuristics that lead to an easy algorithm to solve them. On the other hand, constraint satisfaction problems with a large problem domain may take an inordinate [...]]]></description>
			<content:encoded><![CDATA[<p>In Computing science artificial intelligence terms, the game of Sudoku is a <a href="http://en.wikipedia.org/wiki/Constraint_satisfaction">constraint satisfaction</a> <a href="http://en.wikipedia.org/wiki/Constraint_satisfaction_problem">problem</a>. Constraint satisfaction problems are nice in the regard that there are some very nice heuristics that lead to an easy algorithm to solve them. On the other hand, constraint satisfaction problems with a large problem domain may take an inordinate amount of time to solve.</p>
<p>Sudoku consists of a 9&#215;9 grid, with each grid cell having a possible 9 different values. If we ignore all the constraints, this gives a possible 9^81 boards (1.9662705 × 10^77). Say we can check one-hundred trillion boards a second (100,000,000,000), it would still take ((9^81)/100000000000)/(31556926) = 6.23 × 10^58 years to iterate over all possible combinations! Clearly randomly generating boards and checking if the constraints are fulfilled is not a realistic solution.<br />
<span id="more-190"></span><br />
Instead, we will implement a <a href="http://en.wikipedia.org/wiki/Backtracking">backtracking</a> algorithm. In a nutshell, backtracking incrementally builds a solution, buy iteratively assigning possible values and then checking the validity of the assignment against the constraints. If a constraint doesn&#8217;t hold, the algorithm immediately backtracks, pruning any other possible (wrong) solution that involved that illegal value.</p>
<p>For efficiency&#8217;s sake, we want to prune an incorrect solution as early as possible &#8211; that is to say, we want to assign values to a maximally constrained cell. To do this, we want to be assigning values to a maximally constrained cell. </p>
<p>For example, in Sudoku, if we are examining 3 cells in a single row: C1, C2 and C3 and C1 has one legal value (3), C2 has 4 legal values (1,5,3,2) and C3 has 2 legal values (4,3). Obviously we will want to assign the value 3 to C1 (C1=3) first, then 4 to C3 (C3=4), and then figure out C2 down the line.</p>
<p>What if we didn&#8217;t assign the value 3 to C1 first, and instead assigned 3 to C2 (C2=3)? Then we would have C3=4, and when we come to assign C1, there are no legal values left, so we have wasted traversing this entire branch!</p>
<p>With Backtracking, and early pruning in mind we can develop the following algorithm:</p>
<pre>
 Let c(j,k) be the cell in column j and row k.
 Let V(j,k) be the number of valid values on cell c(j,k).
 Let v(j,k,i) be a valid value for a cell.

 1. Calculate the possible values for every cell c(j,k) that doesnt have a value v(j,k,i) assigned
   if every cell has a value, done.
 2. Find the cell cxy, such that for all a, b, V(x,y) < V(a,b). That is to say, find the cell with the least number of possible values.
   if V(x,y) = 1 (only one possible value)
   	assign c(x,y) = v(x,y,1)
   	goto 1
   else
    foreach value m in v(x,y)
    	assign c(x,y) = m
    	goto 1
</pre>
<p>To summarize, find the cell that is most constrained (least valid assignments). If there is a single valid assignment, make the assignment and recurse, otherwise, foreach valid assignment, assign the value, and recurse.</p>
<p>In JavaScript, step 1 will look like:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">/**
* Gets the values in a given row (meaning iterate through all the columns),
* across all te blocks
*
* @param	int	row			The row to get the column values for
* @param	int	blockRow	The row the block is in (1, 2, 3)
*/</span>
getRowValues<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>row<span style="color: #339933;">,</span> blockRow<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> values <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> bcol<span style="color: #339933;">=</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> bcol<span style="color: #339933;">&lt;=</span><span style="color: #CC0000;">3</span><span style="color: #339933;">;</span> bcol<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span> <span style="color: #003366; font-weight: bold;">var</span> col<span style="color: #339933;">=</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> col<span style="color: #339933;">&lt;=</span><span style="color: #CC0000;">3</span><span style="color: #339933;">;</span> col<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #003366; font-weight: bold;">var</span> value <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>._boardState<span style="color: #009900;">&#91;</span>blockRow<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>bcol<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>row<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>col<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">value</span><span style="color: #339933;">;</span>
			<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>is_numeric<span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				values<span style="color: #009900;">&#91;</span>values.<span style="color: #660066;">length</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> value<span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">return</span> values<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
<span style="color: #006600; font-style: italic;">/**
* Gets all the values in a given column (meaning iterate through all rows),
* accross all the blocks
*
* @param	int	column		The column to get the row values for
* @param	int	columnRow	The column the block is in (1, 2, 3)
*/</span>
getColumnValues<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>col<span style="color: #339933;">,</span> blockCol<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> values <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> brow<span style="color: #339933;">=</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> brow<span style="color: #339933;">&lt;=</span><span style="color: #CC0000;">3</span><span style="color: #339933;">;</span> brow<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span> <span style="color: #003366; font-weight: bold;">var</span> row<span style="color: #339933;">=</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> row<span style="color: #339933;">&lt;=</span><span style="color: #CC0000;">3</span><span style="color: #339933;">;</span> row<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #003366; font-weight: bold;">var</span> value <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>._boardState<span style="color: #009900;">&#91;</span>brow<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>blockCol<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>row<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>col<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">value</span><span style="color: #339933;">;</span>
			<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>is_numeric<span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				values<span style="color: #009900;">&#91;</span>values.<span style="color: #660066;">length</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> value<span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">return</span> values<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
getBlockValues<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>blockRow<span style="color: #339933;">,</span> blockCol<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> values <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> row<span style="color: #339933;">=</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> row<span style="color: #339933;">&lt;=</span><span style="color: #CC0000;">3</span><span style="color: #339933;">;</span> row<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> col<span style="color: #339933;">=</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> col<span style="color: #339933;">&lt;=</span><span style="color: #CC0000;">3</span><span style="color: #339933;">;</span> col<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #003366; font-weight: bold;">var</span> value <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>._boardState<span style="color: #009900;">&#91;</span>blockRow<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>blockCol<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>row<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>col<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">value</span><span style="color: #339933;">;</span>
			<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>is_numeric<span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				values<span style="color: #009900;">&#91;</span>values.<span style="color: #660066;">length</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> value<span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">return</span> values<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
<span style="color: #006600; font-style: italic;">/**
* Gets all possible legal values a cell may possess
*/</span>
getValidCellValues<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>blockRow<span style="color: #339933;">,</span> blockCol<span style="color: #339933;">,</span> row<span style="color: #339933;">,</span> col<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> possibleValues <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span><span style="color: #CC0000;">2</span><span style="color: #339933;">,</span><span style="color: #CC0000;">3</span><span style="color: #339933;">,</span><span style="color: #CC0000;">4</span><span style="color: #339933;">,</span><span style="color: #CC0000;">5</span><span style="color: #339933;">,</span><span style="color: #CC0000;">6</span><span style="color: #339933;">,</span><span style="color: #CC0000;">7</span><span style="color: #339933;">,</span><span style="color: #CC0000;">8</span><span style="color: #339933;">,</span><span style="color: #CC0000;">9</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
	possibleValues <span style="color: #339933;">=</span> array_diff<span style="color: #009900;">&#40;</span>possibleValues<span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getRowValues</span><span style="color: #009900;">&#40;</span>row<span style="color: #339933;">,</span> blockRow<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	possibleValues <span style="color: #339933;">=</span> array_diff<span style="color: #009900;">&#40;</span>possibleValues<span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getColumnValues</span><span style="color: #009900;">&#40;</span>col<span style="color: #339933;">,</span> blockCol<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	possibleValues <span style="color: #339933;">=</span> array_diff<span style="color: #009900;">&#40;</span>possibleValues<span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getBlockValues</span><span style="color: #009900;">&#40;</span>blockRow<span style="color: #339933;">,</span> blockCol<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">return</span> possibleValues<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>We get all the values that appear in the current row, the current column, and the local block (3x3 section the cell is in).<br />
Starting with all the possible assignments, we subtract off any values that appear in the current row, column, or block.</p>
<p>Step 2 is written as:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">calculateAllValidCellValues<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> unsolvedCells <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//Value of current Minimum</span>
<span style="color: #003366; font-weight: bold;">var</span> currentMin <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
	brow<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>
	bcol<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>
	row<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>
	col<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>
	count<span style="color: #339933;">:</span> <span style="color: #CC0000;">10</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//loop through all values</span>
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> brow<span style="color: #339933;">=</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> brow<span style="color: #339933;">&lt;=</span><span style="color: #CC0000;">3</span><span style="color: #339933;">;</span> brow<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> bcol<span style="color: #339933;">=</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> bcol<span style="color: #339933;">&lt;=</span><span style="color: #CC0000;">3</span><span style="color: #339933;">;</span> bcol<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> row<span style="color: #339933;">=</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> row<span style="color: #339933;">&lt;=</span><span style="color: #CC0000;">3</span><span style="color: #339933;">;</span> row<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> col<span style="color: #339933;">=</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> col<span style="color: #339933;">&lt;=</span><span style="color: #CC0000;">3</span><span style="color: #339933;">;</span> col<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>empty<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>._boardState<span style="color: #009900;">&#91;</span>brow<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>bcol<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>row<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>col<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">value</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
					unsolvedCells <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
					<span style="color: #003366; font-weight: bold;">var</span> validCellValues <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getValidCellValues</span><span style="color: #009900;">&#40;</span>brow<span style="color: #339933;">,</span> bcol<span style="color: #339933;">,</span> row<span style="color: #339933;">,</span> col<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
					<span style="color: #000066; font-weight: bold;">this</span>._boardState<span style="color: #009900;">&#91;</span>brow<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>bcol<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>row<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>col<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">validValues</span> <span style="color: #339933;">=</span> validCellValues<span style="color: #339933;">;</span>
&nbsp;
					<span style="color: #006600; font-style: italic;">//we want to find a maximally constrained cell</span>
					<span style="color: #003366; font-weight: bold;">var</span> valueCount <span style="color: #339933;">=</span> count<span style="color: #009900;">&#40;</span>validCellValues<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
					<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>valueCount <span style="color: #339933;">&lt;</span> currentMin.<span style="color: #660066;">count</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
						currentMin.<span style="color: #660066;">brow</span> <span style="color: #339933;">=</span> brow<span style="color: #339933;">;</span>
						currentMin.<span style="color: #660066;">bcol</span> <span style="color: #339933;">=</span> bcol<span style="color: #339933;">;</span>
						currentMin.<span style="color: #660066;">row</span> <span style="color: #339933;">=</span> row<span style="color: #339933;">;</span>
						currentMin.<span style="color: #660066;">col</span> <span style="color: #339933;">=</span> col<span style="color: #339933;">;</span>
						currentMin.<span style="color: #660066;">count</span> <span style="color: #339933;">=</span> valueCount<span style="color: #339933;">;</span>
					<span style="color: #009900;">&#125;</span>
&nbsp;
					<span style="color: #006600; font-style: italic;">//special break-early case because if we find a value count of 1 we can just go ahead</span>
					<span style="color: #006600; font-style: italic;">//and assign it!</span>
					<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>valueCount <span style="color: #339933;">==</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
							<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span>._boardState<span style="color: #009900;">&#91;</span>currentMin.<span style="color: #660066;">brow</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>currentMin.<span style="color: #660066;">bcol</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>currentMin.<span style="color: #660066;">row</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>currentMin.<span style="color: #660066;">col</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
					<span style="color: #009900;">&#125;</span>
				<span style="color: #009900;">&#125;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>unsolvedCells<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #006600; font-style: italic;">//return the maximally constrained cell</span>
	<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span>._boardState<span style="color: #009900;">&#91;</span>currentMin.<span style="color: #660066;">brow</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>currentMin.<span style="color: #660066;">bcol</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>currentMin.<span style="color: #660066;">row</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span>currentMin.<span style="color: #660066;">col</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #000066; font-weight: bold;">else</span><span style="color: #009900;">&#123;</span>
	<span style="color: #006600; font-style: italic;">//We have solved all the cells</span>
	<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span></pre></div></div>

<p>In this step all the possible values are calulated and tallied, and the maximally constrained cell is returned.</p>
<p>Finally, we have the sub-parts of step 2 where the assignment and recurive calls are implemented:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">/**
* if DieOnError is true, will throw an exception if
* and halt execution if an error is thrown. (This should be set to true, for the
* primary board, but not for any &quot;cloned&quot; sub-boards
*/</span>
solveBoard<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>dieOnError<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">try</span><span style="color: #009900;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">do</span><span style="color: #009900;">&#123;</span>
			console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'iteration '</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">++</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">iteration</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #006600; font-style: italic;">//get a maximally constrained cell</span>
			<span style="color: #003366; font-weight: bold;">var</span> cell <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">calculateAllValidCellValues</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>cell <span style="color: #339933;">===</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Solved all cells'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">break</span><span style="color: #339933;">;</span>	<span style="color: #006600; font-style: italic;">//we solved all the cells</span>
			<span style="color: #009900;">&#125;</span>
&nbsp;
			<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>count<span style="color: #009900;">&#40;</span>cell.<span style="color: #660066;">validValues</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				<span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #3366CC;">'Cant find a solution'</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span><span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>count<span style="color: #009900;">&#40;</span>cell.<span style="color: #660066;">validValues</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				<span style="color: #006600; font-style: italic;">//Assign the value and go to the next step</span>
				<span style="color: #003366; font-weight: bold;">var</span> value <span style="color: #339933;">=</span> reset<span style="color: #009900;">&#40;</span>cell.<span style="color: #660066;">validValues</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
				console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'setting ['</span> <span style="color: #339933;">+</span> cell.<span style="color: #660066;">brow</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">']['</span> <span style="color: #339933;">+</span> cell.<span style="color: #660066;">bcol</span> <span style="color: #339933;">+</span><span style="color: #3366CC;">']['</span><span style="color: #339933;">+</span> cell.<span style="color: #660066;">row</span> <span style="color: #339933;">+</span><span style="color: #3366CC;">']['</span><span style="color: #339933;">+</span> cell.<span style="color: #660066;">col</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">']: '</span> <span style="color: #339933;">+</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
				<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">setCellValue</span><span style="color: #009900;">&#40;</span>value<span style="color: #339933;">,</span> cell.<span style="color: #660066;">brow</span><span style="color: #339933;">,</span> cell.<span style="color: #660066;">bcol</span><span style="color: #339933;">,</span> cell.<span style="color: #660066;">row</span><span style="color: #339933;">,</span> cell.<span style="color: #660066;">col</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span><span style="color: #000066; font-weight: bold;">else</span><span style="color: #009900;">&#123;</span>
				<span style="color: #006600; font-style: italic;">//There is more than one possible value</span>
				console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;More than one possible outcome. Creating Sub-boards&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span>i <span style="color: #000066; font-weight: bold;">in</span> cell.<span style="color: #660066;">validValues</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
					<span style="color: #003366; font-weight: bold;">var</span> board <span style="color: #339933;">=</span> dojo.<span style="color: #660066;">clone</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
					<span style="color: #003366; font-weight: bold;">var</span> value <span style="color: #339933;">=</span> cell.<span style="color: #660066;">validValues</span><span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
					console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'setting ['</span> <span style="color: #339933;">+</span> cell.<span style="color: #660066;">brow</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">']['</span> <span style="color: #339933;">+</span> cell.<span style="color: #660066;">bcol</span> <span style="color: #339933;">+</span><span style="color: #3366CC;">']['</span><span style="color: #339933;">+</span> cell.<span style="color: #660066;">row</span> <span style="color: #339933;">+</span><span style="color: #3366CC;">']['</span><span style="color: #339933;">+</span> cell.<span style="color: #660066;">col</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">']: '</span> <span style="color: #339933;">+</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
					board.<span style="color: #660066;">setCellValue</span><span style="color: #009900;">&#40;</span>value<span style="color: #339933;">,</span> cell.<span style="color: #660066;">brow</span><span style="color: #339933;">,</span> cell.<span style="color: #660066;">bcol</span><span style="color: #339933;">,</span> cell.<span style="color: #660066;">row</span><span style="color: #339933;">,</span> cell.<span style="color: #660066;">col</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
					<span style="color: #003366; font-weight: bold;">var</span> subBoardResult <span style="color: #339933;">=</span> board.<span style="color: #660066;">solveBoard</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
					<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>subBoardResult <span style="color: #339933;">!==</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
						<span style="color: #006600; font-style: italic;">//We got a board solution</span>
						console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Sub-board solved all cells'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
						<span style="color: #000066; font-weight: bold;">return</span> subBoardResult<span style="color: #339933;">;</span>
					<span style="color: #009900;">&#125;</span>
				<span style="color: #009900;">&#125;</span>
&nbsp;
				<span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #3366CC;">'Cant find a solution'</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #009900;">&#125;</span><span style="color: #000066; font-weight: bold;">while</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #000066; font-weight: bold;">catch</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>dieOnError<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			console.<span style="color: #660066;">debug</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span></pre></div></div>

<p>Note how we check to see if there is a single valid value, and if not, a sub-board is spawned where each possible value for the maximally constrained cell is explored.</p>
<p>Finally, see it in action for yourself:</p>
<p><a href='http://dustint.com/wp-content/uploads/2010/03/sudoku1.html'>Javascript Sudoku Solver</a></p>
]]></content:encoded>
			<wfw:commentRss>http://dustint.com/archives/190/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Shellinabox Gentoo Init Script</title>
		<link>http://dustint.com/archives/177</link>
		<comments>http://dustint.com/archives/177#comments</comments>
		<pubDate>Tue, 27 Oct 2009 02:24:44 +0000</pubDate>
		<dc:creator>Dustin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[Linux]]></category>

		<guid isPermaLink="false">http://dustint.com/?p=177</guid>
		<description><![CDATA[I&#8217;ve been playing around with ShellInABox and I think it is quite neat. From the website: Shell In A Box implements a web server that can export arbitrary command line tools to a web based terminal emulator. This emulator is accessible to any JavaScript and CSS enabled web browser and does not require any additional [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing around with <a href="http://code.google.com/p/shellinabox/">ShellInABox</a> and I think it is quite neat. From the website:</p>
<blockquote><p>Shell In A Box implements a web server that can export arbitrary command line tools to a web based terminal emulator. This emulator is accessible to any JavaScript and CSS enabled web browser and does not require any additional browser plugins.</p></blockquote>
<p>So basically it gives you a shell to your local system wherever you go (as long as you have a browser that was released since the turn of the century). This can be especially handy if you are on a public machine without permissions to install software (such as putty). The only dis-advantage is that the remote machine has to be running shellinabox, so this will not work for shared hosting environments. However, if  you setup a shellinabox machine, you can then SSH into other boxes that aren&#8217;t running the daemon.</p>
<p>I&#8217;m running Gentoo Linux on my utility machine, and shellinabox doesn&#8217;t ship with a gentoo init script. Please enjoy the one I have written below. Basically, you install shellinabox normally, then I copied its generated certs to /var/lib/shellingabox to be used for ssh connections.</p>
<p>Corrections and improvements are appreciated.</p>
<p>/etc/init.d/shellinaboxd:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/sbin/runscript</span>
<span style="color: #666666; font-style: italic;"># Copyright 1999-2009 Gentoo Foundation</span>
<span style="color: #666666; font-style: italic;"># Distributed under the terms of the GNU General Public License v2</span>
<span style="color: #666666; font-style: italic;"># $Header: $</span>
&nbsp;
<span style="color: #007800;">CMD</span>=<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>local<span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span>shellinaboxd
<span style="color: #007800;">CERT_DIR</span>=<span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>shellinabox
<span style="color: #007800;">PIDFILE</span>=<span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>run<span style="color: #000000; font-weight: bold;">/</span>shellinabox.pid
&nbsp;
depend<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
        need net
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
start<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
        ebegin <span style="color: #ff0000;">&quot;Starting Shellinabox&quot;</span>
        start-stop-daemon <span style="color: #660033;">--start</span> <span style="color: #660033;">--pidfile</span> <span style="color: #007800;">$PIDFILE</span> <span style="color: #660033;">--exec</span> <span style="color: #007800;">$CMD</span> <span style="color: #660033;">--</span> <span style="color: #660033;">--cert</span> <span style="color: #007800;">$CERT_DIR</span> <span style="color: #660033;">-b</span>=<span style="color: #007800;">$PIDFILE</span>
        eend <span style="color: #007800;">$?</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://dustint.com/archives/177/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inject Dojo Bookmark</title>
		<link>http://dustint.com/archives/170</link>
		<comments>http://dustint.com/archives/170#comments</comments>
		<pubDate>Tue, 08 Sep 2009 19:12:36 +0000</pubDate>
		<dc:creator>Dustin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://dustint.com/?p=170</guid>
		<description><![CDATA[Sometimes it can be handy to inject Dojo into pages that would not otherwise have it. I&#8217;ve used this so I can use dojo.query() on a page to select DOM objects while testing a parser in a different language. Use drag this link into your bookmarks and have Dojo at your fingertips no matter where [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes it can be handy to inject Dojo into pages that would not otherwise have it. I&#8217;ve used this so I can use dojo.query() on a page to select DOM objects while testing a parser in a different language.</p>
<p>Use drag this link into your bookmarks and have Dojo at your fingertips no matter where your browser takes you:<br />
<a href="javascript:(function(){djConfig={afterOnLoad:true};e=document.createElement('script');e.type='text/javascript';e.src='http://o.aolcdn.com/dojo/1.3.2/dojo/dojo.xd.js';document.getElementsByTagName('head')[0].appendChild(e);})()">Inject Dojo v.1.3.2</a></p>
]]></content:encoded>
			<wfw:commentRss>http://dustint.com/archives/170/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zend Framework Doctrine Model Autoloader</title>
		<link>http://dustint.com/archives/137</link>
		<comments>http://dustint.com/archives/137#comments</comments>
		<pubDate>Wed, 26 Aug 2009 09:30:42 +0000</pubDate>
		<dc:creator>Dustin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[Autoload]]></category>
		<category><![CDATA[Doctrine]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://dustint.com/?p=137</guid>
		<description><![CDATA[There have been several tutorials outlining how to autoload Doctrine Models using the Zend_Loader_Autoloader. However, none of these have permitted Zend / PEAR style naming conventions for models. I prefer to use these conventions because, although it makes my model names longer, the &#8220;name-spacing&#8221; gives a certain degree of organization and order to the application. [...]]]></description>
			<content:encoded><![CDATA[<p>There have been several tutorials outlining how to autoload Doctrine Models using the Zend_Loader_Autoloader. However, none of these have permitted Zend / PEAR style naming conventions for models. I prefer to use these conventions because, although it makes my model names longer, the &#8220;name-spacing&#8221; gives a certain degree of organization and order to the application.<br />
<span id="more-137"></span><br />
For example, lets say we have two classes (and two tables) in our database. The first class is a very simple person model. A person has an Id, which is used at the primary key, and a name. This person class would be described in YAML notation as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">App_Model_Person:
 tableName: T_person
 columns:
  id: integer
  name: string(64)</pre></div></div>

<p>People have addresses. One person may have more than one address (billing, mailing, physical, for example). Therefore, we need a second, person address table similar to the following:</p>

<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">App_Model_Person_Address:
 tableName: T_person_address
 package: Person
 columns:
  person_id: integer
  address: string</pre></div></div>

<p>Notice that the App_Model_Person_Addres model is in the <em>Person</em> package. This is done to ensure that it will be placed in the person subfolder, so the final path of this class will be App/Model/Person/App_Model_Person_Address.php</p>
<p>Before, using the doctrine command line tool to generate the classes, we must make sure that we are going to generate the models in the appropriate location. Assuming that we have an application library on the include path (eg: library/ is on the include path and it has a folder App in it), then we want Doctrine generating the models in the <em>library/App/Model</em> folder. This can be done by setting the <em>models_path</em> to the proper location. Eg:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">new</span> Doctrine_Cli<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
<span style="color: #339933;">...,</span>
<span style="color: #0000ff;">'models_path'</span>         <span style="color: #339933;">=&gt;</span>  APPLICATION_PATH <span style="color: #339933;">.</span> <span style="color: #0000ff;">'/library/App/Model'</span><span style="color: #339933;">,</span>
<span style="color: #339933;">...</span>
<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The main problem with the auto-generated classes produced by the Doctrine_Cli is the filename of the php file that is generated. For, example, the full path of the generated App_Model_Person class will be <em>library/App/Model/App_Model_Person.php</em>; however, according to Zend conventions it should be <em>library/App/Model/Person.php</em>. </p>
<p>The Doctrine Model Autoloader provided below attempts to solve these problems by detecting when a Doctrine Model is being loaded, and then generating the appropriate path (with the full class name acting as the filename). To complicate matters, there are some special cases for base-classes and package classes as well, specifically that they may have <em>Base</em> or <em>Package</em> prefixing the name of the class. The Model autoloader addresses this by detecting the presence of these terms using regular expressions and tweaking the generation of the paths accordingly.</p>
<p>It is very simple to use the Doctrine Model Autoloader class. Simply instantiate it, passing it the prefix of the Doctrine Model namespace. In this case it would be <em>App_Model_</em>. Don&#8217;t forget the trailing underscore (&#8220;_&#8221;), however the class should detect that its missing and add it in for you if you do. </p>
<p>An example usage for the above case would be simply:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$doctrineAutoloader</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Zext_Loader_Autoloader_DoctrineModel<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'App_Model_'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Upon instantiation, the autoloader registers itself with the Zend_Loader_Autoloader for the passed namepace, so no further setup is required.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Zext_Loader_Autoloader_DoctrineModel implements Zend_Loader_Autoloader_Interface
<span style="color: #009900;">&#123;</span>
	<span style="color: #009933; font-style: italic;">/**
	 * The namespace of the models
	 * @var string
	 */</span>
	protected <span style="color: #000088;">$_namespace</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Whether or not to suppress file not found warnings
     * @var bool
     */</span>
	protected <span style="color: #000088;">$_suppressNotFoundWarnings</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * 
	 * @param string $modelNamespace	The namespace of the model to load. Eg: 'Zext_Model_'
	 * @param boolean $quiet			If this is true, suppresses warnings if the file isn't found
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #000088;">$modelNamespace</span><span style="color: #339933;">,</span> <span style="color: #000088;">$quiet</span><span style="color: #339933;">=</span><span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">strrpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$modelNamespace</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'_'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #cc66cc;">1</span> <span style="color: #339933;">!=</span> <span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$modelNamespace</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$modelNamespace</span> <span style="color: #339933;">.=</span> <span style="color: #0000ff;">'_'</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_namespace <span style="color: #339933;">=</span> <span style="color: #000088;">$modelNamespace</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_suppressNotFoundWarnings <span style="color: #339933;">=</span> <span style="color: #000088;">$quiet</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Initializes Zend_Loader_Autoloader, pushing the doctrine autoloader onto the autoloading stack
	 * @return void
	 */</span>
	protected <span style="color: #000000; font-weight: bold;">function</span> _init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$namespaces</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
			<span style="color: #0000ff;">'Package'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_namespace<span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'Base'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_namespace<span style="color: #339933;">,</span>
			<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_namespace
		<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000088;">$autoloader</span> <span style="color: #339933;">=</span> Zend_Loader_Autoloader<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$namespaces</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$namespace</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$autoloader</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">pushAutoloader</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">,</span> <span style="color: #000088;">$namespace</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * (non-PHPdoc)
	 * @see tests/library/Zend/Loader/Autoloader/Zend_Loader_Autoloader_Interface#autoload($class)
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> autoload<span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">class_exists</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> interface_exists<span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
        <span style="color: #666666; font-style: italic;">//Check to see if we are loading a package / base</span>
        <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'/(?P&lt;prefix&gt;.+)'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_namespace  <span style="color: #339933;">.</span> <span style="color: #0000ff;">'(?P&lt;class&gt;.+)/mx'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$className</span><span style="color: #339933;">,</span> <span style="color: #000088;">$matches</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$result</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$matches</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'prefix'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">strtolower</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$matches</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'prefix'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				<span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'package'</span><span style="color: #339933;">:</span>
					<span style="color: #000088;">$classPath</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_loadPackage<span style="color: #009900;">&#40;</span><span style="color: #000088;">$matches</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'class'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
&nbsp;
				<span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'base'</span><span style="color: #339933;">:</span>
					<span style="color: #000088;">$classPath</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_loadBase<span style="color: #009900;">&#40;</span><span style="color: #000088;">$matches</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'class'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #b1b100;">else</span><span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$classPath</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_getPath<span style="color: #009900;">&#40;</span>
				<span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #990000;">strrpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'_'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> 
				<span style="color: #000088;">$className</span>
			<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
		<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_suppressNotFoundWarnings<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        	<span style="color: #339933;">@</span>Zend_Loader<span style="color: #339933;">::</span><span style="color: #004000;">loadFile</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$classPath</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #b1b100;">else</span><span style="color: #009900;">&#123;</span>
			Zend_Loader<span style="color: #339933;">::</span><span style="color: #004000;">loadFile</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$classPath</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">class_exists</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #339933;">!</span>interface_exists<span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        	<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Gets the correct path for loading packages
	 * 
	 * @param $className
	 * @return string
	 */</span>
	protected <span style="color: #000000; font-weight: bold;">function</span> _loadPackage<span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$package</span> <span style="color: #339933;">=</span> <span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #990000;">strpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'_'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_getPath<span style="color: #009900;">&#40;</span>
			<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_namespace <span style="color: #339933;">.</span> <span style="color: #0000ff;">'packages_'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$package</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'_'</span><span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'Package'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_namespace <span style="color: #339933;">.</span> <span style="color: #000088;">$className</span>
		<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Gets the correct path for loading bases
	 * 
	 * @param $className
	 * @return string
	 */</span>
	protected <span style="color: #000000; font-weight: bold;">function</span> _loadBase<span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$package</span> <span style="color: #339933;">=</span> <span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #990000;">strpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$className</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'_'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_getPath<span style="color: #009900;">&#40;</span>
			<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_namespace <span style="color: #339933;">.</span> <span style="color: #000088;">$package</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'_generated_'</span><span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'Base'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_namespace <span style="color: #339933;">.</span> <span style="color: #000088;">$className</span>
		<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Gets the classpath from an _ separated path and the classname
	 * 
	 * @param string $path
	 * @param string $name
	 * @return string
	 */</span>
	protected <span style="color: #000000; font-weight: bold;">function</span> _getPath<span style="color: #009900;">&#40;</span><span style="color: #000088;">$path</span><span style="color: #339933;">,</span> <span style="color: #000088;">$name</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'_'</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">DIRECTORY_SEPARATOR</span><span style="color: #339933;">,</span> <span style="color: #000088;">$path</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$name</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'.php'</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://dustint.com/archives/137/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building a PHP Publish / Subscribe System</title>
		<link>http://dustint.com/archives/38</link>
		<comments>http://dustint.com/archives/38#comments</comments>
		<pubDate>Tue, 28 Jul 2009 07:14:21 +0000</pubDate>
		<dc:creator>Dustin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[Event]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[publish subscribe]]></category>

		<guid isPermaLink="false">http://dustint.com/?p=38</guid>
		<description><![CDATA[First post in a while. I have been busy working on some large application and finishing up my Computing Science Degree. Now that the piece of paper is safely secured above my fireplace, I&#8217;ve been trying to find time to do a new post. I have been building a large application and one of the [...]]]></description>
			<content:encoded><![CDATA[<p>First post in a while. I have been busy working on some large application and finishing up my Computing Science Degree. Now that the piece of paper is safely secured above my fireplace, I&#8217;ve been trying to find time to do a new post.</p>
<p>I have been building a large application and one of the requirements is to trigger a certain action when an event happens. For example, trigger the sending of an alert email when a database row is updated. Some programmers may be tempted to simply hard-code this functionality into the model class, however this doesn&#8217;t give very strict class encapsulation, and can quickly become un-maintainable.</p>
<p>I use the Dojo Javscript toolkit for most of my dynamic front-end functionality. It has implemented a <a href="http://en.wikipedia.org/wiki/Publish/subscribe">publish/subscribe system</a> using  <a href="http://docs.dojocampus.org/dojo/publish"><code>dojo.publish()</code></a> and <a href="http://docs.dojocampus.org/dojo/subscribe"><code>dojo.subscribe()</code></a>. This article will describe the implementation of a similar system using PHP.<span id="more-38"></span></p>
<h1>Overview</h1>
<p>The concept I wanted to implement consists of three parts:</p>
<ol>
<li><strong>The Listener</strong><br />
This is a class that is interested in the events that are thrown by some other class. Keeping with the above example, tihs class may implement the functionality of sending the alert emails when the database row is updated</li>
<li><strong>The Event</strong><br />
To give the listener some data to act on, an event (message) is passed from the triggering object to the listener. This event may contain information such as the column values for the updated row.</li>
<li><strong>The Dispatcher</strong><br />
The dispatcher is the glue that holds everything together. When an object wants to trigger and event it passes it to the dispatcher <em>(publishes it)</em>. When a listener class wants to listen for an event, it will ask the dispatcher to inform it when the event of a specified type is passed (<em>subscribe</em>).</li>
</ol>
<p>Some other food for thought:</p>
<ul>
<li>A listener may only want to subscribe to an event that is published by a certain resource, so there must be a way to track who published the event</li>
<li>A listener may want to subscribe to all events that are published by a resource or to a specific event independent of the resource, so wildcards should be permitted</li>
</ul>
<h1>Implementation</h1>
<h2>The Event Object</h2>
<p>The event object, in its simplicity, is a very basic class. As mentioned above, it needs to track a minimum of:</p>
<ol>
<li>The resource that published the event</li>
<li>The name (/type) of the event</li>
<li>Some (optional) data to be passed to the listener</li>
</ol>
<p>A very simple example of an event object may be the following:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Event <span style="color: #009900;">&#123;</span>
	<span style="color: #009933; font-style: italic;">/**
	 * The name of the resource publishing this event
	 * @var string
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$resourceName</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * The name of this event
	 * @var string
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$eventName</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Any data associated with this event
	 * @var mixed
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$data</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * @param string $resourceName	name of the publisher
	 * @param string $eventName		name of the event
	 * @param mixed $data			[OPTIONAL] Additional event data
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #000088;">$resourceName</span><span style="color: #339933;">,</span> <span style="color: #000088;">$eventName</span><span style="color: #339933;">,</span> <span style="color: #000088;">$data</span><span style="color: #339933;">=</span><span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">resourceName</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$resourceName</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">eventName</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$eventName</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">data</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$data</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Depending on your goals, you may want to make $resourceName, $eventName, and $data private attributes and use getters / setters. Additionally, if you do not wish to pass the eventName and, rather, use object inheritance you could implement the event object in either of the following ways:</p>
<p>Eg 1: Manually set the event name.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> UpdateEvent <span style="color: #000000; font-weight: bold;">extends</span> Event
<span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$eventName</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Update'</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #000088;">$resourceName</span><span style="color: #339933;">,</span> <span style="color: #000088;">$data</span><span style="color: #339933;">=</span><span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">resourceName</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$resourceName</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">data</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$data</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Eg 2: Automatically parse the event name from the class name</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> UpdateEvent <span style="color: #000000; font-weight: bold;">extends</span> Event
<span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #000088;">$resourceName</span><span style="color: #339933;">,</span> <span style="color: #000088;">$data</span><span style="color: #339933;">=</span><span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		parent<span style="color: #339933;">::</span>__construct<span style="color: #009900;">&#40;</span><span style="color: #000088;">$resourceName</span><span style="color: #339933;">,</span> <span style="color: #990000;">get_class</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$data</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h2>The Listener Object</h2>
<p>The Listener object is also has a very simple job. It simply accepts an event object and does something with it. The only catch is that all listener objects should have the same method which accepts the event. Because of this, it makes sense to use an interface.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">interface</span> ListenerInterface
<span style="color: #009900;">&#123;</span>
	<span style="color: #009933; font-style: italic;">/**
	 * Accepts an event and does something with it
	 *
	 * @param Event $event	The event to process
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> publish<span style="color: #009900;">&#40;</span>Event <span style="color: #000088;">$event</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I am going to implement a very simple listener class for the purpose of this demo. This listener outputs a string saying what event was fired, and for which resource. EG:  published a .</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> EchoListener implements ListenerInterface
<span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> publish<span style="color: #009900;">&#40;</span>Event <span style="color: #000088;">$event</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;<span style="color: #006699; font-weight: bold;">{$event-&gt;resourceName}</span> published a <span style="color: #006699; font-weight: bold;">{$event-&gt;eventName}</span>&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h2>The Dispatch Object</h2>
<p>The dispatch object is by far the most complex of all the components. It handles both the subscription of listeners and the dispatching of events. For my actual implementation I needed more than one backend for my dispatch object (Both a hard-coded memory based one, and a user-defined backend based on mysql). For simplicities sake I am going to demonstrate only the memory-based backend here, and leave the implementation of multiple-backends as an exercise to the user.</p>
<p>Without further adeau, here is the class in its entirety. I will discuss each part individually below:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Dispatcher <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #009933; font-style: italic;">/**
     * Associative array of listeners.
     * Indicies are: [resourceName][event][listener hash]
     *
     * @var array
     */</span>
    protected <span style="color: #000088;">$_listeners</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #009933; font-style: italic;">/**
     * Subscribes the listener to the resource's events.
     * If $resourceName is *, then the listener will be dispatched when the specified event is fired
     * If $event is *, then the listener will be dispatched for any dispatched event of the specified resource
     * If $resourceName and $event is *, the listener will be dispatched for any dispatched event for any resource
     *
     * @param Listener $listener
     * @param String $resourceName
     * @param Mixed $event
     * @return Dispatcher
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> subscribe<span style="color: #009900;">&#40;</span>Listener <span style="color: #000088;">$listener</span><span style="color: #339933;">,</span> <span style="color: #000088;">$resourceName</span><span style="color: #339933;">=</span><span style="color: #0000ff;">'*'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$event</span><span style="color: #339933;">=</span><span style="color: #0000ff;">'*'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    	<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_listeners<span style="color: #009900;">&#91;</span><span style="color: #000088;">$resourceName</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$event</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #990000;">spl_object_hash</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$listener</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$listener</span><span style="color: #339933;">;</span>
    	<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #009933; font-style: italic;">/**
     * Unsubscribes the listener from the resource's events
     *
     * @param Listener $listener
     * @param String $resourceName
     * @param Mixed $event
     * @return Dispatcher
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> unsubscribe<span style="color: #009900;">&#40;</span>Listener <span style="color: #000088;">$listener</span><span style="color: #339933;">,</span> <span style="color: #000088;">$resourceName</span><span style="color: #339933;">=</span><span style="color: #0000ff;">'*'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$event</span><span style="color: #339933;">=</span><span style="color: #0000ff;">'*'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    	<span style="color: #990000;">unset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_listeners<span style="color: #009900;">&#91;</span><span style="color: #000088;">$resourceName</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$event</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #990000;">spl_object_hash</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$listener</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    	<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #009933; font-style: italic;">/**
     * Publishes an event to all the listeners listening to the specified event for the specified resource
     *
     * @param Event $event
     * @return Dispatcher
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> publish<span style="color: #009900;">&#40;</span>Event <span style="color: #000088;">$event</span> <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    	<span style="color: #000088;">$resourceName</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$event</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">resourceName</span><span style="color: #339933;">;</span>
    	<span style="color: #000088;">$eventName</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$event</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">eventName</span><span style="color: #339933;">;</span>
&nbsp;
    	<span style="color: #666666; font-style: italic;">//Loop through all the wildcard handlers</span>
    	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_listeners<span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'*'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'*'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	    	<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_listeners<span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'*'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'*'</span><span style="color: #009900;">&#93;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$listener</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	    		<span style="color: #000088;">$listener</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">publish</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$event</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	    	<span style="color: #009900;">&#125;</span>
    	<span style="color: #009900;">&#125;</span>
&nbsp;
    	<span style="color: #666666; font-style: italic;">//Dispatch wildcard Resources</span>
    	<span style="color: #666666; font-style: italic;">//These are events that are published no matter what the resource</span>
    	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_listeners<span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'*'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	    	<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_listeners<span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'*'</span><span style="color: #009900;">&#93;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$event</span> <span style="color: #339933;">=&gt;;</span> <span style="color: #000088;">$listeners</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	    		<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$event</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$eventName</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	    			<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$listeners</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$listener</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	    				<span style="color: #000088;">$listener</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">publish</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$event</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	    			<span style="color: #009900;">&#125;</span>
	    		<span style="color: #009900;">&#125;</span>
	    	<span style="color: #009900;">&#125;</span>
    	<span style="color: #009900;">&#125;</span>
&nbsp;
    	<span style="color: #666666; font-style: italic;">//Dispatch wildcard Events</span>
    	<span style="color: #666666; font-style: italic;">//these are listeners that are dispatched for a certain resource, despite the event</span>
    	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_listeners<span style="color: #009900;">&#91;</span><span style="color: #000088;">$resourceName</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'*'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    		<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_listeners<span style="color: #009900;">&#91;</span><span style="color: #000088;">$resourceName</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'*'</span><span style="color: #009900;">&#93;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$listener</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
   				<span style="color: #000088;">$handler</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">publish</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$event</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    		<span style="color: #009900;">&#125;</span>
    	<span style="color: #009900;">&#125;</span>
&nbsp;
    	<span style="color: #666666; font-style: italic;">//Dispatch to a certain resource event</span>
    	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_listeners<span style="color: #009900;">&#91;</span><span style="color: #000088;">$resourceName</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$eventName</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    		<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_handlers<span style="color: #009900;">&#91;</span><span style="color: #000088;">$resourceName</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$eventName</span><span style="color: #009900;">&#93;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$listener</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    			<span style="color: #000088;">$handler</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">publish</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$event</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    		<span style="color: #009900;">&#125;</span>
    	<span style="color: #009900;">&#125;</span>
&nbsp;
    	<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>Listeners Attribute</h3>
<p>This associative array tracks all the listeners that are subscribed to events. It supports wildcard resources and wildcard events, allowing for a listener to be subscribed to a certain event and resource, all events of a certain resource, all events of a certain type, or all events across all resources. By having an object hash as the final key, well permit multiple listeners to be subscribed to a single event, while still maintaining the unsubscribe functionality (assuming the original object is still present).</p>
<h3>Subscribe Function</h3>
<p>The subscribe function subscribes a listener to either a specific event for a specific resource and event pairing, or some combination of wildcards.</p>
<h3>Unsubscribe Function</h3>
<p>Unsubscribes a listener from a resource&#8217;s event or wildcard.</p>
<h3>Publish Function</h3>
<p>The publish function is the workhorse of the Dispatcher class. Every time an event is pubished, the dispatcher searches through the listener array, looking first for any global wildcards (listeners that should be informed on any event), then resource wildcards (listeners that are subscribed to a certain event across all resources), then event wildcards (listeners that are subcribed to all events of a certain resource), and finally events that are subscribed to only one resource&#8217;s event.</p>
<h1>Putting It Together</h1>
<p>Now that we have our three components built, it is time to put it all together. First setup the dispatcher and subscribe some listeners to a resource&#8217;s event. Next, publish the event to the dispatcher and, fingers crossed, the event should be propogated to your listeners.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$dispatcher</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Dispatcher<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$echoListener</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> EchoListener<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$dispatcher</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">subscribe</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$echoListener</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'fooResource'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'barEvent'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Should output &quot;fooResource published a barEvent&quot;</span>
<span style="color: #000088;">$dispatcher</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">publish</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Event<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'fooResource'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'barEvent'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Well that was a lot of writing. There are several ways to extend this model to make it a bit more elegant and efficient (such as having the publisher of an event pass an instance of itself &#8211; this is especially useful for database models, having the subscribe rules dynamically loaded based on the resource name via, say, Zend_Plugin_Loader, having the resource name automatically filled in in much the same way that the event name can be populated); however, I hope this has given you a starting point from which to implement events in your application.</p>
<p>If you have any questions / find spelling, grammar or coding mistakes please mention them in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://dustint.com/archives/38/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Per Module Zend_Layout</title>
		<link>http://dustint.com/archives/28</link>
		<comments>http://dustint.com/archives/28#comments</comments>
		<pubDate>Wed, 06 Aug 2008 03:18:53 +0000</pubDate>
		<dc:creator>Dustin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[Zend_Controller_Plugin]]></category>
		<category><![CDATA[Zend_Layout]]></category>

		<guid isPermaLink="false">http://dustint.com/?p=28</guid>
		<description><![CDATA[Sometimes when you are building a web application, you want to use different layouts for different parts of the site. For example, in a content management system, you may want one layout for normal users and another, completely different layout for site administrators. Assuming that you have the standard zend directory structure, you will have [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes when you are building a web application, you want to use different layouts for different parts of the site. For example, in a content management system, you may want one layout for normal users and another, completely different layout for site administrators. <span id="more-28"></span></p>
<p>Assuming that you have the standard zend directory structure, you will have something like this:</p>
<pre>/application
  /admin
    /controllers
    /layouts
    /views
  /default
    /controllers
    /layouts
    /views
  /feeds
    /controllers
    /views</pre>
<p>Or something of the sort. When the user is in the admin section we want to use the layout folder from /admin, and when they are in the default section or in the feeds section of the site we would like to use the layout folder from /default.</p>
<p>We could simply go through all the controllers in the admin section and set the layout path in the init or preDisptach function:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> preDispatch<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	Zend_Layout<span style="color: #339933;">::</span><span style="color: #004000;">getMvcInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setLayoutPath</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'../application/admin/layouts'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This may work well for this simple example. However, every time we wish to add a controller to the admin section it would be necessary to setup the layout path and if ever we want to change the layout path for the admin module, there would be a lot of search-replacing.</p>
<p>A Much better solution is to write a plugin for the Zend Front controller. This plugin extends the Zend_Controller_Plugin_Abstract type and will be run each time the front controller is invoked, before anything is rendered.</p>
<p>Our plugin must have some very basic functionality:</p>
<ol>
<li>Ability to register a layout for use with a specified module</li>
<li>Ability to fall back to the default layout if there is no layout registered for the current module</li>
</ol>
<p>The Layout Plugin is as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Module_LayoutPlugin <span style="color: #000000; font-weight: bold;">extends</span> Zend_Controller_Plugin_Abstract <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Array of layout paths associating modules with layouts
	 */</span>
	protected <span style="color: #000088;">$_moduleLayouts</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Registers a module layout.
	 * This layout will be rendered when the specified module is called.
	 * If there is no layout registered for the current module, the default layout as specified
	 * in Zend_Layout will be rendered
	 * 
	 * @param String $module		The name of the module
	 * @param String $layoutPath	The path to the layout
	 * @param String $layout		The name of the layout to render
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> registerModuleLayout<span style="color: #009900;">&#40;</span><span style="color: #000088;">$module</span><span style="color: #339933;">,</span> <span style="color: #000088;">$layoutPath</span><span style="color: #339933;">,</span> <span style="color: #000088;">$layout</span><span style="color: #339933;">=</span><span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_moduleLayouts<span style="color: #009900;">&#91;</span><span style="color: #000088;">$module</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
			<span style="color: #0000ff;">'layoutPath'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$layoutPath</span><span style="color: #339933;">,</span>
			<span style="color: #0000ff;">'layout'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$layout</span>
		<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> preDispatch<span style="color: #009900;">&#40;</span>Zend_Controller_Request_Abstract <span style="color: #000088;">$request</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_moduleLayouts<span style="color: #009900;">&#91;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getModuleName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$config</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_moduleLayouts<span style="color: #009900;">&#91;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getModuleName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #000088;">$layout</span> <span style="color: #339933;">=</span> Zend_Layout<span style="color: #339933;">::</span><span style="color: #004000;">getMvcInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$layout</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getMvcEnabled</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				<span style="color: #000088;">$layout</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setLayoutPath</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$config</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'layoutPath'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
				<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$config</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'layout'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">!==</span> <span style="color: #009900; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
					<span style="color: #000088;">$layout</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setLayout</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$config</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'layout'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #009900;">&#125;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The $_moduleLayouts property maintains the mapping between modules and layouts.</p>
<p>The registerModuleLayout function allows us to register a layoutpath and an (optional) layout name for a module. </p>
<p>The actual magic happens in the preDispatch function (which is called by the front controller before dispatching the request). The function checks to see if there is a layout set for the current module; if there is, it switches the layout path to use the module-specific path. Next it checks to see if there is a layout name associated with the layout registered for this module. If there is, it uses it, otherwise it falls back to the default layout name.</p>
<p>In our bootstrapper file (html/index.php) we must setup the default layout and module layout paths and then register the plugin with the front controller. The following code snippit is only a sliver of the bootstrapper and assumes that $controller is an instance of Zend_Controller_Front (eg: $controller = Zend_Controller_Front::getInstance();)</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//setup the layout</span>
Zend_Layout<span style="color: #339933;">::</span><span style="color: #004000;">startMvc</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #0000ff;">'layoutPath'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'../application/default/layouts'</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'layout'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'main'</span>
<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$layoutModulePlugin</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Module_LayoutPlugin<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$layoutModulePlugin</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">registerModuleLayout</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'admin'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'../application/admin/layouts'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$controller</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">registerPlugin</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$layoutModulePlugin</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>It is important to setup the default layout so the plugin has a layout to fall back to if no module-specific layout is registered. </p>
<p>I hope that this tutorial has served as a quick and easy introduction to Zend Front Controller plugins and module-specific layouts.</p>
]]></content:encoded>
			<wfw:commentRss>http://dustint.com/archives/28/feed</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Cache-Control with Zend Framework</title>
		<link>http://dustint.com/archives/25</link>
		<comments>http://dustint.com/archives/25#comments</comments>
		<pubDate>Fri, 06 Jun 2008 02:45:37 +0000</pubDate>
		<dc:creator>Dustin</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[Cache-Control]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://dustint.com/?p=25</guid>
		<description><![CDATA[Today I was optimizing a site that uses heavy PHP and Ajax. I wanted to reduce the amount of data that was being sent from the server. To put this in perspective, if there were no cache hits in a page load there would be a total of 755 KB pulled down over 123 requests. [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was optimizing a site that uses heavy PHP and Ajax. I wanted to reduce the amount of data that was being sent from the server. To put this in perspective, if there were no cache hits in a page load there would be a total of 755 KB pulled down over 123 requests.<br />
<span id="more-25"></span><br />
The first step was throwing a .htaccess into the dojo folder that sets the Cache-Control header on the library files being pulled down.</p>

<div class="wp_syntax"><div class="code"><pre class="apache" style="font-family:monospace;">&lt;<span style="color: #000000; font-weight:bold;">IfModule</span> mod_expires.c&gt;
     <span style="color: #00007f;">Header</span> set Cache-Control <span style="color: #7f007f;">&quot;max-age=3600, public&quot;</span>
&lt;/<span style="color: #000000; font-weight:bold;">IfModule</span>&gt;</pre></div></div>

<p>The above checks to ensure the mod_expires module is loaded in apache, and if it is the Cache is set to expire 3600 seconds from now: 1 hour. Furthermore, the page can be cached in a publicly accessible (shared) cache.</p>
<p>Getting caching working with Zend was a little more challenging. By default Zend (or PHP) writes caching information to headers disabling caching. However, the code snippit below (to be placed inside an Action Controller) blanks out the expires header, sets the cache-control header so that the page expires in one hour, and blanks out the Pragma header. </p>
<p>The expires header allows the server to specify a date when the cache expires (Rather than setting the max-age offset) and the Pragma indicates if the page can be cached in a proxy. I found, with Firefox 3, if Expires and Pragma weren&#8217;t blanked out, they would take preference over the Cache-Control header, disabling caching of the page.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getResponse</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setHeader</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Expires'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getResponse</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setHeader</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Cache-Control'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'public'</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getResponse</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setHeader</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Cache-Control'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'max-age=3800'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getResponse</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setHeader</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Pragma'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>After the addition of caching, the page load was reduced to 8Kb of data pulled down over 9 requests: about a 90% optimization.</p>
]]></content:encoded>
			<wfw:commentRss>http://dustint.com/archives/25/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
