<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Mathayi's Blog</title>
	<atom:link href="http://mathayi.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://mathayi.wordpress.com</link>
	<description>Just another WordPress.com weblog</description>
	<lastBuildDate>Mon, 21 Dec 2009 12:35:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='mathayi.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Mathayi's Blog</title>
		<link>http://mathayi.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://mathayi.wordpress.com/osd.xml" title="Mathayi&#039;s Blog" />
	<atom:link rel='hub' href='http://mathayi.wordpress.com/?pushpress=hub'/>
		<item>
		<title>INTERNALS OF SESSIONS</title>
		<link>http://mathayi.wordpress.com/2009/05/18/internals-of-sessions/</link>
		<comments>http://mathayi.wordpress.com/2009/05/18/internals-of-sessions/#comments</comments>
		<pubDate>Mon, 18 May 2009 02:47:10 +0000</pubDate>
		<dc:creator>mathayi</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[internals_of_session]]></category>
		<category><![CDATA[session]]></category>
		<category><![CDATA[sessions_php]]></category>

		<guid isPermaLink="false">http://mathayi.wordpress.com/?p=50</guid>
		<description><![CDATA[INTERNALS OF SESSIONS When the session_start is called, PHP is looking for an argument from the client (sent via POST, GET or Cookie) with the name of session.name to retrieve the session ID. If it finds a valid session ID (there are some syntactical restrictions), it tries to retrieve the session data from the storage [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=50&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>INTERNALS OF SESSIONS</strong></p>
<p style="text-align:left;">When the session_start is called, PHP is looking for an argument from the client (sent via POST, GET or Cookie) with the name of session.name to retrieve the session ID.</p>
<p style="text-align:left;">If it finds a valid session ID (there are some syntactical restrictions), it tries to retrieve the session data from the storage (session.save_handler) to store it in $_SESSION.</p>
<p style="text-align:left;">If it can’t find an ID or the configuration forbids its usage (see session.use_cookies, session.use_only_cookies and session.use_trans_sid), PHP generates a new ID using a hash function (session.hash_function) on data of a source that generates random data (session.entropy_file).</p>
<p>At the end of the runtime, it stores the $_SESSION data in the designated storage.</p>
<p><strong>1.	Will session works, if cookies are disabled?</strong><br />
NO. In this case each call to session_start will generate a new ID as it can’t  find the previous ID.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathayi.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathayi.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mathayi.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mathayi.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mathayi.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mathayi.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mathayi.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mathayi.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mathayi.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mathayi.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mathayi.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mathayi.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mathayi.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mathayi.wordpress.com/50/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=50&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathayi.wordpress.com/2009/05/18/internals-of-sessions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6b6115bcb8fd0e144662eb67264cc416?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathayi</media:title>
		</media:content>
	</item>
		<item>
		<title>MVC architecture in PHP development</title>
		<link>http://mathayi.wordpress.com/2009/01/19/mvc-architecture-in-php-development/</link>
		<comments>http://mathayi.wordpress.com/2009/01/19/mvc-architecture-in-php-development/#comments</comments>
		<pubDate>Mon, 19 Jan 2009 10:50:35 +0000</pubDate>
		<dc:creator>mathayi</dc:creator>
				<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://mathayi.wordpress.com/?p=44</guid>
		<description><![CDATA[MVC stands for Model-View-Controller. It is a type of architecture for developing software, recently pretty popular in web applications development. In short, the three things are pretty simple. Model is what interacts with the database, it would be the backend class code for an object-oriented language like PHP, Ruby on Rails, or C++. View is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=44&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>MVC stands for Model-View-Controller. It is a type of architecture for developing software, recently pretty popular in web applications development. In short, the three things are pretty simple. Model is what interacts with the database, it would be the backend class code for an object-oriented language like PHP, Ruby on Rails, or C++. View is basically the user interface. Controller is the logic that operates everything in between.</p>
<p>They are easy to explain, but sometimes the concept is a little abstract and it’s hard to grasp for someone who doesn’t know what MVC is to begin with. To be honest, all my years in web development I never really understood exactly what MVC is, until recently when I started doing development in Ruby on Rails. In this article, I hope to explain MVC architecture development in PHP terms, so the average web apps programmer may benefit from understanding this powerful architecture.</p>
<p><strong>MVC and PHP development</strong></p>
<p>The reason I mentioned Ruby on Rails is because you really have to understand how to develop an application with the MVC architecture to do anything at all on RoR. (Next time, I will write another article on RoR — but this time, I’ll talk about PHP development.)</p>
<p>The Model-View-Controller separation actually makes a lot of sense, it is actually natural for a developer to divide his/her code that way when working on a reasonably large application. Java has classes, JSP and struts; Ruby on Rails has a built-in MVC structure; but even when PHP doesn’t have anything like that, it doesn’t mean you can’t do it.</p>
<p><strong>The Model</strong></p>
<p>The MVC structure is meant for reasonably-sized applications, using object-oriented coding. The Model part, in a PHP app, would usually be a class (or multiple classes). Fairly often, the class is a representation of a table you store in the database — member variables are the data columns, and member methods are operations that can be done. As an example, you might have a User class, having variables such as username, password, email address, and other things. Some of its methods might be a new user creation function, a login function, an authentication function, and a logout function.</p>
<p>Later on, we will see how User objects will be used in the Controller part of your application. The Model, in essence, tells you what methods are available — what <em>can</em> you do to the data in the database. I thought I should just clarify (if it wasn’t clear already) — this should be all PHP code, just as what you should do in OO-programming even without MVC. There should be no HTML or any kinds of outputs (redirection, etc.) here. If doing an action means that a redirection is needed or some output is needed, pass it as an argument or a return value. (It’s fairly basic programming practices, but you’d be surprised how many web apps programmers didn’t graduate with a CS degree..)</p>
<p>Here’s an example of the Model part of your code. Of course, there will be many more classes in a real application. This is just the code is the simplest form, without a lot of the details.</p>
<blockquote>
<pre>class User
{
   var $username;
   var $password;
   var $email;
   function User($u, $p, $e) // constructor
   {
      $this-&gt;username = $u;
      $this-&gt;password = $p;
      $this-&gt;email = $e;
   }
   function create()
   {
      // creates user in the db
   }
   function login()
   {
      // checks against db, does login procedures
   }
   static function authenticate($u, $p)
   {
      // checks against db
   }
   function logout()
   {
      // does logout procedures
   }
}</pre>
</blockquote>
<p><strong>The View</strong></p>
<p>The View, in the simplest words, is the user interface. However, it doesn’t mean it would be just straight HTML. Minimal PHP logic will need to be used in your application’s interface a lot of times. For example, if you were to have the main logged-in page say, “Hello, [username]!” You would certainly need some PHP code to handle that, right? That is all part of the View. Of course, all the CSS, Javascript would be part of this too.</p>
<p>It is important that whatever PHP code in here is only what needs to be used to display the interface correctly. No additional “action” code belongs to the View — that is the Controller’s job, which we’ll see next.</p>
<p>This was easy to understand, but for clarification’s sake, let’s see an example anyway. Of course, the following isn’t even valid XHTML 1.0 (it lacks a DOCTYPE, for instance), but this is just an example.</p>
<blockquote>
<pre>&lt;?php
require_once('User.php');
// makes sure user isn't already logged in
if (User::authenticate($_COOKIE['username'], $_COOKIE['password']))
{
   header(”Location:/main.php”);
   exit();
}
?&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;Please login&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Login&lt;/h1&gt;
&lt;?
if ($_GET['error'] == 1)
{
   echo ‘Login incorrect. Please try again.&lt;br /&gt;’;
}
?&gt;
&lt;form action=”login_action.php” method=”post”&gt;
User: &lt;input type=”text” name=”username” /&gt;&lt;br /&gt;
Pass: &lt;input type=”password” name=”password” /&gt;&lt;br /&gt;
&lt;input type=”submit” value=”Login” /&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
</blockquote>
<p><strong>The Controller</strong></p>
<p>Sometimes it is confusing to understand what the Controller needs to do, if you weren’t working on an actual application and just reading a book/an article. It would seem like the Model and the View are all you need. So let’s go back to a concrete PHP example.</p>
<p>Now imagine you have a login page setup. The login HTML form has to submit to somewhere, right? (Even if you’re using AJAX) You don’t submit directly to the Model class file (say, User.php), because that file only contains the class code, and no actual procedural code is there, so it won’t do anything. You certainly don’t submit directly back to the View file (say, login.php), even if it ends with a .php extension! Because its job is only to display the interface.</p>
<p>This is what the Controller is. Your form will submit to a file, say, login_action.php. In this file, you create an instance of the User class, running whatever initialization you need, and calling the appropriate methods that need to be run (login).</p>
<p>Some developers fall into the temptation to display outputs from the Controller, because it’s convenient. Imagine, if you had a login form, how easy is it to just print “Login incorrect” directly from the Controller PHP code? (assuming you aren’t using AJAX, for this particular example) It is an option, and I will tell you that many scripts do just that. However, to truly utilize a MVC structure’s advantage, the Controller (like the Model) should not display any HTML outputs, but rather use redirection. You may use cookies/sessions, database storage, flat file caching, or query string to the View file to store the states of your application; and then you should always let the View take care of displaying outputs, using these stored states.</p>
<p>Now let’s see an example of a Controller code.</p>
<blockquote>
<pre>&lt;?php
require_once('User.php');
// in reality, a lot more error checking needs to be done.
$currentuser = new User($_POST['username'], $_POST['password'], ”);
if ($currentuser-&gt;login())
{
   // set cookies for login info
   header(”Location:/main.php”);
   exit();
}
else
{
   header(”Location:/login.php?error=1″);
   exit();
}
?&gt;</pre>
</blockquote>
<p><strong>Conclusion</strong></p>
<p>Using the MVC structure, code becomes a lot easier to understand. For other developers to join in to understand your code, as well as for yourself in the future when you come back to it after a while. Development is also a lot easier because you know exactly where to look for what piece of code. If you were going to change some message displaying in the interface, you only need to go to the View. If your database structure sees a change, such as passwords now encrypting in a different way, you only need to change your Model. The MVC architecture is very powerful and makes your object-oriented web apps development a lot more efficient.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathayi.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathayi.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mathayi.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mathayi.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mathayi.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mathayi.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mathayi.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mathayi.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mathayi.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mathayi.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mathayi.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mathayi.wordpress.com/44/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mathayi.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mathayi.wordpress.com/44/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=44&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathayi.wordpress.com/2009/01/19/mvc-architecture-in-php-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6b6115bcb8fd0e144662eb67264cc416?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathayi</media:title>
		</media:content>
	</item>
		<item>
		<title>Create a PHP web crawler or scraper in 5 minutes</title>
		<link>http://mathayi.wordpress.com/2009/01/19/create-a-php-web-crawler-or-scraper-in-5-minutes/</link>
		<comments>http://mathayi.wordpress.com/2009/01/19/create-a-php-web-crawler-or-scraper-in-5-minutes/#comments</comments>
		<pubDate>Mon, 19 Jan 2009 10:36:46 +0000</pubDate>
		<dc:creator>mathayi</dc:creator>
				<category><![CDATA[Web Crawling]]></category>
		<category><![CDATA[screen scrapper]]></category>

		<guid isPermaLink="false">http://mathayi.wordpress.com/?p=42</guid>
		<description><![CDATA[Utilizing the PHP programming language we show you how to create an infinitely extendable web crawler in under 5 minutes, collecting images and links. The Crawler Framework First we need to create the crawler class as follows: &#60;?php class Crawler { } ?&#62; We then will create methods to fetch the web pages markup, and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=42&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Utilizing the PHP programming language we show you how to create an infinitely extendable web crawler in under 5 minutes, collecting images and links.</p>
<h2>The Crawler Framework</h2>
<p>First we need to create the crawler class as follows:</p>
<div class="codeblock"><code><span style="color:#000000;"><span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#007700;">class </span><span style="color:#0000bb;">Crawler </span><span style="color:#007700;">{</p>
<p>}</p>
<p></span><span style="color:#0000bb;">?&gt;</span></span></code></div>
<p>We then will create methods to fetch the web pages markup, and to parse it for data that we are looking at collecting. The only public methods will be getMarkup() and get() as the parsing methods will generally be used privately for the crawler, however the visibility is set to protected since you never know who will want to extend its functionality.</p>
<div class="codeblock"><code><span style="color:#000000;"><span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#007700;">class </span><span style="color:#0000bb;">Crawler </span><span style="color:#007700;">{</p>
<p>protected</p>
<p></span><span style="color:#0000bb;">$markup </span><span style="color:#007700;">= </span><span style="color:#dd0000;">''</span><span style="color:#007700;">;</p>
<p>public function</p>
<p></span><span style="color:#0000bb;">__construct</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$uri</span><span style="color:#007700;">) {</p>
<p>}</p>
<p>public function</p>
<p></span><span style="color:#0000bb;">getMarkup</span><span style="color:#007700;">() {</p>
<p>}</p>
<p>public function</p>
<p></span><span style="color:#0000bb;">get</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$type</span><span style="color:#007700;">) {</p>
<p>}</p>
<p>protected function</p>
<p></span><span style="color:#0000bb;">_get_images</span><span style="color:#007700;">() {</p>
<p>}</p>
<p>protected function</p>
<p></span><span style="color:#0000bb;">_get_links</span><span style="color:#007700;">() {</p>
<p>}<br />
}</p>
<p></span><span style="color:#0000bb;">?&gt;</span></span></code></div>
<h2>Fetching Site Markup</h2>
<p>The constructor will accept a URI so we can instantiate it such as new Crawler(&#8216;http://vision-media.ca&#8217;); which then will set our $markup property using PHP&#8217;s file_get_contents() function which fetches the sites markup.</p>
<div class="codeblock"><code><span style="color:#000000;"><span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#007700;">public function </span><span style="color:#0000bb;">__construct</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$uri</span><span style="color:#007700;">) {<br />
</span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">markup </span><span style="color:#007700;">= </span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">getMarkup</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$uri</span><span style="color:#007700;">);<br />
}</p>
<p>public function</p>
<p></span><span style="color:#0000bb;">getMarkup</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$uri</span><span style="color:#007700;">) {<br />
return </span><span style="color:#0000bb;">file_get_contents</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$uri</span><span style="color:#007700;">);<br />
}<br />
</span><span style="color:#0000bb;">?&gt;</span></span></code></div>
<h2>Crawling The Markup For Data</h2>
<p>Our get() method will accept a $type string which essentially will simply be used to invoke another method actually doing the processing. As you can see below we construct the method name as a string, then make sure it is available so now developers can utilize this simply by invoking $crawl-&gt;get(&#8216;images&#8217;);</p>
<p>We set visibility for _get_images() and _get_links() to protected so that developers will use our public get() method rather than getting confused and trying to invoke them directly.</p>
<p>Each protected data collection method simply uses the <a href="http://www.pcre.org/">PCRE (Perl Compatible Regular Expressions)</a> function preg_match_all() in order to return all tags within the markup that are accepted using our patterns of <strong>/&lt;img([^&gt;]+)\/&gt;/i</strong> and  <strong>/&lt;a([^&gt;]+)\&gt;(.*?)\&lt;\/a\&gt;/i</strong>. For more information on regular expressions visit <a title="http://en.wikipedia.org/wiki/Regular_expression" href="http://en.wikipedia.org/wiki/Regular_expression">http://en.wikipedia.org/wiki/Regular_expression</a></p>
<div class="codeblock"><code><span style="color:#000000;"><span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#007700;">public function </span><span style="color:#0000bb;">get</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$type</span><span style="color:#007700;">) {<br />
</span><span style="color:#0000bb;">$method </span><span style="color:#007700;">= </span><span style="color:#dd0000;">"_get_{$type}"</span><span style="color:#007700;">;<br />
if (</span><span style="color:#0000bb;">method_exists</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$this</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$method</span><span style="color:#007700;">)){<br />
return </span><span style="color:#0000bb;">call_user_method</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$method</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$this</span><span style="color:#007700;">);<br />
}<br />
}</p>
<p>protected function</p>
<p></span><span style="color:#0000bb;">_get_images</span><span style="color:#007700;">() {<br />
if (!empty(</span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">markup</span><span style="color:#007700;">)){<br />
</span><span style="color:#0000bb;">preg_match_all</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'/&lt;img([^&gt;]+)\/&gt;/i'</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">markup</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$images</span><span style="color:#007700;">);<br />
return !empty(</span><span style="color:#0000bb;">$images</span><span style="color:#007700;">[</span><span style="color:#0000bb;">1</span><span style="color:#007700;">]) ? </span><span style="color:#0000bb;">$images</span><span style="color:#007700;">[</span><span style="color:#0000bb;">1</span><span style="color:#007700;">] : </span><span style="color:#0000bb;">FALSE</span><span style="color:#007700;">;<br />
}<br />
}</p>
<p>protected function</p>
<p></span><span style="color:#0000bb;">_get_links</span><span style="color:#007700;">() {<br />
if (!empty(</span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">markup</span><span style="color:#007700;">)){<br />
</span><span style="color:#0000bb;">preg_match_all</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'/&lt;a([^&gt;]+)\&gt;(.*?)\&lt;\/a\&gt;/i'</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">markup</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$links</span><span style="color:#007700;">);<br />
return !empty(</span><span style="color:#0000bb;">$links</span><span style="color:#007700;">[</span><span style="color:#0000bb;">1</span><span style="color:#007700;">]) ? </span><span style="color:#0000bb;">$links</span><span style="color:#007700;">[</span><span style="color:#0000bb;">1</span><span style="color:#007700;">] : </span><span style="color:#0000bb;">FALSE</span><span style="color:#007700;">;<br />
}<br />
}<br />
</span><span style="color:#0000bb;">?&gt;</span></span></code></div>
<h2>Final PHP Web Crawler Code And Usage</h2>
<div class="codeblock"><code><span style="color:#000000;"><span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#007700;">class </span><span style="color:#0000bb;">Crawler </span><span style="color:#007700;">{</p>
<p>protected</p>
<p></span><span style="color:#0000bb;">$markup </span><span style="color:#007700;">= </span><span style="color:#dd0000;">''</span><span style="color:#007700;">;</p>
<p>public function</p>
<p></span><span style="color:#0000bb;">__construct</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$uri</span><span style="color:#007700;">) {<br />
</span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">markup </span><span style="color:#007700;">= </span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">getMarkup</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$uri</span><span style="color:#007700;">);<br />
}</p>
<p>public function</p>
<p></span><span style="color:#0000bb;">getMarkup</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$uri</span><span style="color:#007700;">) {<br />
return </span><span style="color:#0000bb;">file_get_contents</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$uri</span><span style="color:#007700;">);<br />
}</p>
<p>public function</p>
<p></span><span style="color:#0000bb;">get</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$type</span><span style="color:#007700;">) {<br />
</span><span style="color:#0000bb;">$method </span><span style="color:#007700;">= </span><span style="color:#dd0000;">"_get_{$type}"</span><span style="color:#007700;">;<br />
if (</span><span style="color:#0000bb;">method_exists</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$this</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$method</span><span style="color:#007700;">)){<br />
return </span><span style="color:#0000bb;">call_user_method</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$method</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$this</span><span style="color:#007700;">);<br />
}<br />
}</p>
<p>protected function</p>
<p></span><span style="color:#0000bb;">_get_images</span><span style="color:#007700;">() {<br />
if (!empty(</span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">markup</span><span style="color:#007700;">)){<br />
</span><span style="color:#0000bb;">preg_match_all</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'/&lt;img([^&gt;]+)\/&gt;/i'</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">markup</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$images</span><span style="color:#007700;">);<br />
return !empty(</span><span style="color:#0000bb;">$images</span><span style="color:#007700;">[</span><span style="color:#0000bb;">1</span><span style="color:#007700;">]) ? </span><span style="color:#0000bb;">$images</span><span style="color:#007700;">[</span><span style="color:#0000bb;">1</span><span style="color:#007700;">] : </span><span style="color:#0000bb;">FALSE</span><span style="color:#007700;">;<br />
}<br />
}</p>
<p>protected function</p>
<p></span><span style="color:#0000bb;">_get_links</span><span style="color:#007700;">() {<br />
if (!empty(</span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">markup</span><span style="color:#007700;">)){<br />
</span><span style="color:#0000bb;">preg_match_all</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'/&lt;a([^&gt;]+)\&gt;(.*?)\&lt;\/a\&gt;/i'</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$this</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">markup</span><span style="color:#007700;">, </span><span style="color:#0000bb;">$links</span><span style="color:#007700;">);<br />
return !empty(</span><span style="color:#0000bb;">$links</span><span style="color:#007700;">[</span><span style="color:#0000bb;">1</span><span style="color:#007700;">]) ? </span><span style="color:#0000bb;">$links</span><span style="color:#007700;">[</span><span style="color:#0000bb;">1</span><span style="color:#007700;">] : </span><span style="color:#0000bb;">FALSE</span><span style="color:#007700;">;<br />
}<br />
}<br />
}</p>
<p></span><span style="color:#0000bb;">$crawl </span><span style="color:#007700;">= new </span><span style="color:#0000bb;">Crawler</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'http://vision-media.ca'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">$images </span><span style="color:#007700;">= </span><span style="color:#0000bb;">$crawl</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">get</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'images'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">$links </span><span style="color:#007700;">= </span><span style="color:#0000bb;">$crawl</span><span style="color:#007700;">-&gt;</span><span style="color:#0000bb;">get</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'links'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">?&gt;</span></span></code></div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathayi.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathayi.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mathayi.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mathayi.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mathayi.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mathayi.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mathayi.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mathayi.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mathayi.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mathayi.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mathayi.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mathayi.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mathayi.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mathayi.wordpress.com/42/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=42&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathayi.wordpress.com/2009/01/19/create-a-php-web-crawler-or-scraper-in-5-minutes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6b6115bcb8fd0e144662eb67264cc416?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathayi</media:title>
		</media:content>
	</item>
		<item>
		<title>Using POST method in XMLHTTPRequest(Ajax)</title>
		<link>http://mathayi.wordpress.com/2009/01/19/using-post-method-in-xmlhttprequestajax/</link>
		<comments>http://mathayi.wordpress.com/2009/01/19/using-post-method-in-xmlhttprequestajax/#comments</comments>
		<pubDate>Mon, 19 Jan 2009 10:28:20 +0000</pubDate>
		<dc:creator>mathayi</dc:creator>
				<category><![CDATA[AJAX]]></category>

		<guid isPermaLink="false">http://mathayi.wordpress.com/?p=38</guid>
		<description><![CDATA[Usually only the GET method is used while creating Ajax apps. But there are several occasions when POST is necessary when creating a ajax request. This could be for several reasons. For example, POST request are considered more secure than GET request as creating a POST request is relatively harder than creating a GET request. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=38&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Usually only the GET method is used while creating <a href="http://www.openjs.com/ajax/">Ajax</a> apps. But there are several occasions when POST is necessary when creating a ajax request. This could be for several reasons. For example, POST request are considered more secure than GET request as creating a POST request is relatively harder than creating a GET request.</p>
<h2>Requirements</h2>
<ul>
<li>Create a XMLHTTPRequest Object that uses the POST method.</li>
<li>See if the arguments passed to it appear in the &#8216;<code>$_POST</code>&#8216; array in <abbr class="Hypertext Preprocessor">PHP</abbr>.</li>
</ul>
<h2>Code</h2>
<h3>XMLHTTPRequest Object</h3>
<p>For the sake of simplicity, we are going to create the XMLHTTPRequest object using the Firefox supported &#8216; XMLHttpRequest()&#8217; function. I believe that you know the proper way of <a title="jx Ajax Library - Line by Line Explaination" href="http://www.openjs.com/scripts/jx/jx.php">creating a cross-browser XMLHttpRequest object</a>. If not, learn that first.</p>
<pre><code class="javascript">var http = new XMLHttpRequest();</code></pre>
<h3>Using GET method</h3>
<p>Now we open a connection using the GET method.</p>
<pre><code class="javascript">
var url = "get_data.php";
var params = "lorem=ipsum&amp;name=binny";
http.open("<span class="special">GET</span>", url<span class="special">+"?"+params</span>, true);
http.onreadystatechange = function() {//Call a function when the state changes.
	if(http.readyState == 4 &amp;&amp; http.status == 200) {
		alert(http.responseText);
	}
}
http.send(<span class="special">null</span>);
</code></pre>
<p>I really hope that this much is clear for you &#8211; I am assuming that you know a bit of Ajax coding. If you don&#8217;t, please read a <a title="A Gentle Introduction to Ajax" href="http://www.openjs.com/ajax/tutorial/">ajax tutorial</a> that explains these parts before continuing.</p>
<h3>POST method</h3>
<p>We are going to make some modifications so POST method will be used when sending the request&#8230;</p>
<pre><code class="javascript">
var url = "get_data.php";
var params = "lorem=ipsum&amp;name=binny";
http.open("<span class="highlight">POST</span>", url, true);

<span class="highlight">//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");</span>

http.onreadystatechange = function() {//Call a function when the state changes.
	if(http.readyState == 4 &amp;&amp; http.status == 200) {
		alert(http.responseText);
	}
}
http.send(<span class="highlight">params</span>);
</code></pre>
<p>The first change(and the most obvious one) is that I changed the first argument of the <code>open</code> function from GET to POST. Also notice the difference in the second argument &#8211; in the GET method, we send the parameters along with the url separated by a &#8216;?&#8217; character&#8230;</p>
<pre><code class="javascript">http.open("GET",<span class="special">url+"?"+params</span>, true);</code></pre>
<p>But in the POST method we will use just the url as the second argument. We will send the parameters later.</p>
<pre><code class="javascript">http.open("POST", <span class="special">url</span>, true);</code></pre>
<p>Some <a title="Header Field Definitions" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">http headers</a> must be set along with any POST request. So we set them in these lines&#8230;</p>
<pre><code class="javascript">http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");</code></pre>
<p>With the above lines we are basically saying that the data send is in the format of a form submission. We also give the length of the parameters we are sending.</p>
<pre><code class="javascript">http.onreadystatechange = function() {//Call a function when the state changes.
	if(http.readyState == 4 &amp;&amp; http.status == 200) {
		alert(http.responseText);
	}
}</code></pre>
<p>We set a handler for the &#8216;ready state&#8217; change event. This is the same handler we used for the GET method. You can use the <code>http.responseText</code> here &#8211; insert into a div using innerHTML(<a class="mypoges blog" title="AHAH(Asynchronous HTML over HTTP) - AJAX 2.0" href="http://binnyva.blogspot.com/2005/11/ahahasynchronous-html-over-http-ajax.html">AHAH</a>), eval it(<a class="blog mypages" title="Ajax Response Data Formats" href="http://binnyva.blogspot.com/2006/03/ajax-response-data-formats.html">JSON</a>) or anything else.</p>
<pre><code class="javascript">http.send(<span class="highlight">params</span>);</code></pre>
<p>Finally, we send the parameters with the request. The given url is loaded only after this line is called. In the GET method, the parameter will be a null value. But in the POST method, the data to be send will be send as the argument of the <code>send</code> function. The <code>params</code> variable was declared in the second line as &#8220;lorem=ipsum&amp;name=binny&#8221; &#8211; so we send two parameters &#8211; &#8216;lorem&#8217; and &#8216;name&#8217; with the values &#8216;ipsum&#8217; and &#8216;binny&#8217; respectively.</p>
<p>That&#8217;s it. If you wish to see the working of this script, I have set up a <a href="http://www.openjs.com/scripts/examples/ajax_using_post.php">demo page for Ajax using post</a>.</p>
<h2>Libraries</h2>
<p>The above given methods are the manual way of doing things &#8211; you can automate this using the hundreds of Ajax libraries out there.</p>
<h3><a href="http://www.openjs.com/scripts/jx/">jx</a></h3>
<pre><code class="javascript">
jx.load("get_data.php?lorem=ipsum&amp;name=binny",handlerFunction,"text","POST");
</code></pre>
<h3>Prototype</h3>
<pre><code class="javascript">var myAjax = new Ajax.Request('get_data.php?lorem=ipsum&amp;name=binny',{
	method: 'post',
	onComplete:handlerFunction
});
</code></pre>
<h3>Dojo Toolkit</h3>
<pre><code class="javascript">dojo.io.bind({
	url:        "get_data.php?lorem=ipsum&amp;name=binny",
	mimetype:   "text/plain",
	method:		"POST",
	load:handlerFunction
});

</code></pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathayi.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathayi.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mathayi.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mathayi.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mathayi.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mathayi.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mathayi.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mathayi.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mathayi.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mathayi.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mathayi.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mathayi.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mathayi.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mathayi.wordpress.com/38/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=38&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathayi.wordpress.com/2009/01/19/using-post-method-in-xmlhttprequestajax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6b6115bcb8fd0e144662eb67264cc416?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathayi</media:title>
		</media:content>
	</item>
		<item>
		<title>Update Multiple Page Elements Using The XMLHTTPRequest Object and JavaScript</title>
		<link>http://mathayi.wordpress.com/2009/01/19/update-multiple-page-elements-using-the-xmlhttprequest-object-and-javascript/</link>
		<comments>http://mathayi.wordpress.com/2009/01/19/update-multiple-page-elements-using-the-xmlhttprequest-object-and-javascript/#comments</comments>
		<pubDate>Mon, 19 Jan 2009 10:20:12 +0000</pubDate>
		<dc:creator>mathayi</dc:creator>
				<category><![CDATA[AJAX]]></category>

		<guid isPermaLink="false">http://mathayi.wordpress.com/?p=35</guid>
		<description><![CDATA[In the development of Ajax application many times we will encounter following issues. The requiremnt to update multiple text boxes simultaneously. Fill more that one dropdown list. Update a combination of text boxes, dropdown lists and div tags. Call different web pages and different webservices at the same time. Imagine the case of a financial [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=35&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the development of Ajax application many times we will encounter following issues.</p>
<ul type="disc">
<li>The requiremnt to update multiple text boxes simultaneously.</li>
<li>Fill more that one dropdown list.</li>
<li>Update a combination of text boxes, dropdown lists and div tags.</li>
<li>Call different web pages and different webservices at the same time.</li>
</ul>
<p>Imagine the case of a financial data site (such as a stock market info site) with various regions of the page used for displaying data any taking user inputs. We may want to populate fill numerous div tags, textboxes and dropdown lists with real time data. If we loop the several requests and we will also have to check for timeout, if timeout occurs and no data is returned, then we will have to fire the same request again. It may end up that we have made 10 requests and 4-5 requests simply timeout because of network problems. If we dont loop then we will either get whole data or nothing (in which case there is only one more request to be made).</p>
<p>In this article we will discuss the XMLHTTPRequest object and JavaScript and develop a JavaScript class which can asychronously update multiple HTML elements. Also this class can be extended as per the requirements. I have used ASP.NET as the platform in this example but it does as the solution is just Javascript it can be applied to any web development platform.</p>
<p>Regarding classes in JavaScript, technically there is no &#8216;class&#8217; in JavaScript but we can use a function as a class.</p>
<p>Consider the following code :</p>
<p class="textCode">function testClass()<br />
{<br />
this.Msg = &#8220;Hello&#8221;;<br />
this.showMsg = function()<br />
{<br />
alert(this.Msg);<br />
}<br />
}</p>
<p>var obj = new testClass();<br />
obj.Msg = &#8220;HI&#8221;;<br />
obj.showMsg();</p>
<p>In above script if we remove <strong>obj.Msg = &#8220;HI&#8221;; </strong>we will get an alert with text Hello.</p>
<p>We will now develop our JavaScript class step-by-step:</p>
<ol type="1">
<li>Include JS file and add the following code:</li>
</ol>
<p><span class="textCode"> function AjaxClass()<br />
{<br />
this.Method = &#8220;GET&#8221;;//OR &#8220;POST&#8221;<br />
this.Async = true; //OR false (asynchronous or synchronous call)<br />
this.request = null;<br />
this.init = function()<br />
{<br />
if (window.XMLHttpRequest) // if Mozilla, Safari etc<br />
this.request = new XMLHttpRequest();<br />
else if (window.ActiveXObject)<br />
{ // if IE<br />
try<br />
{<br />
this.request = new    ActiveXObject(&#8220;Msxml2.XMLHTTP&#8221;);<br />
}<br />
catch (e)<br />
{<br />
try<br />
{<br />
this.request = new ActiveXObject(&#8220;Microsoft.XMLHTTP&#8221;);<br />
}<br />
catch (e){}<br />
}<br />
}</span></p>
<p><span class="textCode"> if(this.request)<br />
{<br />
this.request.onreadystatechange=this.handleResponse;<br />
//we will develope <strong>this.handleResponse</strong> function in step 3<br />
this.request.open(this.Method, this.url , this.Async);<br />
this.request.send(null);<br />
}<br />
}<br />
}</span><br />
Here we have created an XMLHTTPRequest object which is simply used to send a call to the server. The default method is <strong>GET</strong><strong> </strong>(this.Method = &#8220;GET&#8221;)<strong> </strong>and calling type is <strong>Ascynchronous </strong>(this.Async = true)</p>
<ol type="1">
<li>In this step we will develop simple logic which will allow us to dynamically call Ajax function created in Step 1.</li>
</ol>
<p>For this one JSON (<a href="http://www.json.org/">http://www.json.org/</a>) object as follows.</p>
<p class="textCode">this.JSONArray = {  &#8220;Method&#8221; : &#8220;POST&#8221;, //Method type<br />
&#8220;Async&#8221;  : true, //Call type<br />
&#8220;CallPage&#8221; : &#8220;CallPage.aspx&#8221;, //page or webservice<br />
&#8220;Querystring&#8221; : &#8220;&#8221;, //Query string<br />
&#8220;dependentType&#8221; : null,//[0,1,2,3] for isEdit<br />
&#8220;isEdit&#8221;: [<br />
{<br />
"textBoxId" : null, //0 then this element<br />
"dropDownId" : null, //1 then this element<br />
"default" : null, //2 then this element<br />
"misc":null //3 then this element<br />
}<br />
]</p>
<p class="textCode">};</p>
<p>In above script we can set the default values for all elements. We will use these values to set response from the server to textboxes,drop down lists,Div tags, td tags etc. Using &#8220;CallPage&#8221; : &#8220;CallPage.aspx&#8221; we can define default server page and while calling Ajax function we can change this value to web method or to any other web page.<br />
As we will proceed in this article we will examine how to change all the above values and how can we use it to update multiple elements.Also we will see that how to extend the class.</p>
<ol type="1">
<li>Recall from Step 1 : <span class="textCode">this.request.onreadystatechange = this.handleResponse; </span></li>
</ol>
<p>In this step we will develop <span class="textCode">this.handleResponse </span>function and in this function we will use the JSON object defined in Step 2. Whenever <span class="textCode">this.handleResponse</span> function gets called script loses the focus of  <span class="textCode">this. </span>To keep track of this object we will asign it to some variable. i.e <span class="textCode">var self = this; // To lose of focus of the element</span></p>
<p>In this function we will be able to receive data from server. Once we receive the data we can manipulate it. This function will handle the responses from web services as well as from web pages. The web service always returns a response in the form of XML whereas the response from the webpage can be any format defined by web developer.</p>
<p>The function will be as follows:</p>
<p class="textCode">var self = this; // To handle lose of focus<br />
this.handleResponse = function()<br />
{<br />
if(self.request.readyState == 4 &amp;&amp; self.request.status == 200)<br />
{<br />
if (window.ActiveXObject) // for IE<br />
{<br />
var doc=new ActiveXObject(&#8220;Microsoft.XMLDOM&#8221;);<br />
doc.async=&#8221;false&#8221;;<br />
doc.loadXML(self.request.responseText);<br />
}<br />
// code for Mozilla, Firefox, Opera, etc.<br />
else<br />
{<br />
var parser=new DOMParser();<br />
var doc=parser.parseFromString(self.request.responseText,&#8221;text/xml&#8221;);<br />
}<br />
try<br />
{<br />
var data  = &#8220;&#8221;;<br />
if(doc.documentElement) //Response from webservice<br />
data = doc.documentElement.childNodes[0].nodeValue;<br />
else data = self.request.responseText; //from web page<br />
//data contains response text from the server</p>
<p class="textCode">//At this point we have response from serve<br />
//so here we will write our function to    //manipulate the data. We will develop it in<br />
//4th step.<br />
}<br />
catch(e) {}<br />
}<br />
}  <strong></strong></p>
<p><strong></strong></p>
<p>In the the 1st step we had:</p>
<p><span class="textCode">if(this.request)<br />
{<br />
this.request.onreadystatechange=this.handleResponse;<br />
this.request.open(this.Method, this.url , this.Async);<br />
this.request.send(null);<br />
}</span></p>
<p>We will now modify this so that we can directly use the JSON array which we defined in 2nd step:</p>
<p class="textCode">if(this.request)<br />
{<br />
this.request.onreadystatechange=this.handleResponse;<br />
this.request.open(this.JSONArray.Method, this.url , this.JSONArray.Async);<br />
this.request.send(null);<br />
}</p>
<p>While developing Ajax applications we ned to be aware of the following issues regarding domains:</p>
<ul type="disc">
<li>URL for XMLHTTPRequest object should belong to same domain.</li>
<li>Firefox and other browser doesn’t allow cross domain communication.</li>
<li>IE will show warning for cross domain communication.</li>
</ul>
<p>Thus our this.url = “http://myDomain/mysite/&#8221; + this.JSONArray.CallPage + this.JSONArray.Querystring;</p>
<p>e.g. &#8220;http://localhost/Demo/CallPage.aspx?&#8221;+this.JSONArray.Querystring;<br />
Also whenever we want to call web methods like above example, we need to set following protocols under &lt;webServices&gt; in web.config file.</p>
<p><span class="textCode">&lt;webServices&gt;<br />
&lt;protocols&gt;<br />
&lt;add name=&#8221;HttpGet&#8221;/&gt;<br />
&lt;add name=&#8221;HttpPost&#8221;/&gt;<br />
&lt;/protocols&gt;<br />
&lt;/webServices&gt;</span></p>
<ol type="1">
<li>Up to this point we have finished with development of the Ajax logic which will return a response. So now we need to develop logic for updating the HTML controls.</li>
</ol>
<p>In<span class="textCode"> this.handleResponse</span> (step 3) we have seen that we get response in the “data” variable in JavaScript.<br />
<strong> </strong><br />
So now we have response from the server we will add following logic:</p>
<p><span class="textCode">switch(self.JSONArray.dependentType)<br />
{<br />
case 0:<br />
PopulateControls(self.JSONArray.isEdit[0].textBoxId,data);<br />
//simple call to JS function<br />
break;<br />
case 1:<br />
PopulateControls(self.JSONArray.isEdit[0].dropDownId,data);<br />
break;<br />
}</span></p>
<p><span class="textCode"><br />
self.JSONArray.isEdit[0].textBoxId</span> will contain the id of the text box in which we need to update. And <span class="textCode">data </span>is the response from the server. In our switch we have simply used the elements of JSON object developed in Step 2.</p>
<p>We will now focus on initiating a request and setting the elements of the JSON objects.</p>
<p>First simply create object of our AjaxClass().</p>
<p class="textCode">var obj = new AjaxClass(); //Object creation<br />
obj.JSONArray.Method = &#8220;GET&#8221;; //Setting Method<br />
obj.JSONArray.isEdit[0].textBoxId=&#8221;txt1&#8243;;//Textboxid for response<br />
obj.JSONArray.dependentType=0;//0-&gt;Textbox,1-&gt;drop downlist,<br />
//2-&gt;tagId,3-&gt;Misc and so on<br />
obj.init();//Initiate the AjaxCall</p>
<p>If <span class="textCode">obj.JSONArray.dependentType=1</span> then our <strong>switch </strong>case will not work for the textbox, but it will work for a dropdown list (check above <strong>switch </strong>case). This means we will have to set the dropdown in the JSON object:</p>
<p><span class="textCode">obj.JSONArray.isEdit[0].dropDownId=&#8221;ddl1&#8243;;</span></p>
<p>In this way we can define our own set of HTML controls to be updated.</p>
<p>In the same way we can also change all the default settings in JSON object of that class.</p>
<p>e.g.</p>
<p><span class="textCode">obj.JSONArray.Method = &#8220;GET&#8221;;<br />
obj.JSONArray.CallPage = &#8220;Mywebservice/webMethod&#8221;;<br />
obj.JSONArray.Querystring= &#8220;My querystring&#8221;;</span></p>
<p>For this URL will be : <span class="textCode">this.url = this.url + this.JSONArray.CallPage + this.JSONArray.Querystring ; </span><br />
<strong></strong><strong></strong></p>
<p>In case of a web service we will have to set the CallPage element as we did in the above example.</p>
<p>For multiple textboxes use: <span class="textCode">obj.JSONArray.isEdit[0].textBoxId=&#8221;txt1$txt2$txtn&#8221;;//$ is a delimiter</span><br />
While sending data from the server send it with the same delimiter,in such a way when we split obj.JSONArray.isEdit[0].textBoxId and response data on $; we will receive data and the appropriate textBoxId.</p>
<p>Now that we have different types like “txtbox(es) + drop down list(s) + div&#8221; in such case we can use &#8220;misc&#8221; option of isEdit element of JSON object.</p>
<p>And we can define our  <strong>PopulateControls </strong>function the way we want. For ASP.NET we could also integrate ICallback logic for large data transfers.</p>
<p>You can download the demo code <a href="http://www.ajaxmatters.com/code/XMLHTTPJSClassExt.zip">here</a> . This contains an ASP.NET project with the following files:</p>
<ul type="disc">
<li>XMLHTTPJsClass.js this file contains our AjaxClass() and funtion to populate textbox(es).</li>
<li>Demo.js this file contains 3 js function which initiates AjaxRequest with customization of  request. Here you can find web page and webservice calls.</li>
<li>Default.aspx page</li>
<li>Webservice.asmx page.</li>
</ul>
<p><span class="textCode"><br />
</span></p>
<p><span class="textCode"></p>
<div class="nav"></div>
<div class="nav"></div>
<p></span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathayi.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathayi.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mathayi.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mathayi.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mathayi.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mathayi.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mathayi.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mathayi.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mathayi.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mathayi.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mathayi.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mathayi.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mathayi.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mathayi.wordpress.com/35/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=35&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathayi.wordpress.com/2009/01/19/update-multiple-page-elements-using-the-xmlhttprequest-object-and-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6b6115bcb8fd0e144662eb67264cc416?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathayi</media:title>
		</media:content>
	</item>
		<item>
		<title>Getting started with AJAX using PHP</title>
		<link>http://mathayi.wordpress.com/2009/01/19/getting-started-with-ajax-using-php/</link>
		<comments>http://mathayi.wordpress.com/2009/01/19/getting-started-with-ajax-using-php/#comments</comments>
		<pubDate>Mon, 19 Jan 2009 10:15:10 +0000</pubDate>
		<dc:creator>mathayi</dc:creator>
				<category><![CDATA[AJAX]]></category>

		<guid isPermaLink="false">http://mathayi.wordpress.com/?p=32</guid>
		<description><![CDATA[AJAX stands for Asynchronous JavaScript And XML. Any server side technology that supports JavaScript also supports AJAX. AJAX is a browser technology, and is therefore independent of web server platforms. In this article we will learn about what AJAX is, how it works, and how can we use AJAX with PHP. Please remember, AJAX is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=32&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>AJAX stands for Asynchronous JavaScript And XML. Any server side technology that supports JavaScript also supports AJAX. AJAX is a browser technology, and is therefore independent of web server platforms.</p>
<p>In this article we will learn about what AJAX is, how it works, and how can we use AJAX with PHP. Please remember, AJAX is not a programming language, so you don’t have to learn any new technology. AJAX can be implemented by using existing standards (JavaScript and XML) in a different way.</p>
<p>If we are using PHP or any server side technology and need to extract data from storage on a server (eg a database or a file), we will have to make an HTTP request (either POST or GET) to get the data. Once the data is received the the web page will need to be reloaded to show the data. Using AJAX technology we can request and receive the data from server in background and then display it on the page without a reload. AJAX uses HTTP requests for this. With AJAX, JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object (XML over HTTP). With an HTTP request, a web page can make a request to, and get a response from a web server without reloading the page.<br />
The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7. But the creation of XMLHttpRequest object is different in Internet Explorer than the other browsers. I will discuss this later. To use AJAX to request a data from the server we need to do the following.</p>
<p>1. Create an XMLHttpRequest object.<br />
2. Then using this object, request data from the server.<br />
3. JavaScript will then monitor for the changing of state of the request.<br />
4. If the response is successful, then the content from the data store requested will be returned as response (response can be in the form of a String or XML).<br />
5. Use the response in your web page.</p>
<p class="textBoldBlue">1. Create an XMLHttpRequest object</p>
<p>JavaScript has a built-in XMLHttpRequest object. You can use that for Firefox, Safari, and Opera. For Internet Explorer use the ActiveXObject, there is also a difference between IE 5.0 and IE 6.0+ in how to create the object. The following codes creates an XMLHttpRequest for all browsers:</p>
<p class="textCode">var req;</p>
<p class="textCode">if(window.XMLHttpRequest){<br />
//For Firefox, Safari, Opera<br />
req = new XMLHttpRequest();<br />
}<br />
else if(window.ActiveXObject){<br />
//For IE 5<br />
req = new ActiveXObject(&#8220;Microsoft.XMLHTTP&#8221;);<br />
} else if(window.ActiveXObject){<br />
//For IE 6+<br />
req = new ActiveXObject(&#8220;Msxml2.XMLHTTP&#8221;);<br />
}<br />
else{<br />
//Error for an old browser<br />
alert(&#8216;Your browser is not IE 5 or higher, or Firefox or Safari or Opera&#8217;);<br />
}</p>
<p>Here, first we are using the built-in JavaScript function XMLHttpRequest() for creating an XMLHttpRequest for Firefox, Safari and Opera. If the browser does support window.ActiveXObject, then it is Internet Explorer. For IE versions 5.0+, use new ActiveXObject(&#8220;Microsoft.XMLHTTP&#8221;) and for IE 6.0+ use new ActiveXObject(&#8220;Msxml2.XMLHTTP&#8221;). If the browser does not support the built-in JavaScript function XMLHttpRequest() or ActiveXObject, then it does not support AJAX. You can also use JavaScript try-catch blocks for the same output.</p>
<p><span class="textCode">var req;<br />
try<br />
{<br />
// Firefox, Opera, Safari<br />
xmlHttp=new XMLHttpRequest();<br />
}<br />
catch (e)<br />
{<br />
// Internet Explorer<br />
try<br />
{<br />
xmlHttp=new ActiveXObject(&#8220;Msxml2.XMLHTTP&#8221;);<br />
}<br />
catch (e)<br />
{<br />
try<br />
{<br />
xmlHttp=new ActiveXObject(&#8220;Microsoft.XMLHTTP&#8221;);<br />
}<br />
catch (e)<br />
{<br />
alert(&#8216;Your browser is not IE 5 or higher, or Firefox or Safari or Opera&#8217;);<br />
}<br />
}<br />
}</span></p>
<p>In JavaScript, if statements within a try section fail, then the execution resumes from the corresponding catch block. Here first we are trying to get create a XMLHttpRequest using the built-in function, and if it fails then we will try using ActiveXObject(&#8220;Msxml2.XMLHTTP&#8221;), and if it fails also we will try ActiveXObject(&#8220;Microsoft.XMLHTTP&#8221;). If all these fail, then we will alert the user that his/her browser does not support AJAX.</p>
<p class="textBoldBlue">2. Request for a web page</p>
<p>After creating the XMLHttpRequest we now need to send the web request using the open method. We also need to specify the HttpRequest method, GET or POST. Use the following code to send the request.</p>
<p class="textCode">req.open(“GET”,”somedata.php”);<br />
req.send(null);</p>
<p>Here, req is the XMLHttpRequest object. It will request to the server for somedata.php using GET method. The open function also has a third parameter, an optional boolean parameter. You should set that to true :</p>
<p><span class="textCode">req.open(“GET”,”somedata.php”,true);<br />
req.send(null);</span></p>
<p>Both of the above is correct.</p>
<p class="textBoldBlue">3. Monitor for the response of the request</p>
<p>You will need to monitor for the state of the request. For doing this you can assign a function to req.onreadystatechange (Here, req is the XMLHttpRequest object), like below.</p>
<p class="textCode">req.onreadystatechange=function()<br />
{<br />
if(req.readyState==4 &amp;&amp; req.status == 200)<br />
{<br />
var resp = req.responseText;<br />
}<br />
}</p>
<p>Or like this,</p>
<p class="textCode">req.onreadystatechange = handleResponse;</p>
<p><span class="textCode">function handleResponse(){<br />
if(req.readyState == 4 &amp;&amp; req.status == 200){<br />
//returned text from the PHP script<br />
var response = req.responseText;<br />
}<br />
}</span></p>
<p>The readyState property holds the status of the server&#8217;s response. Each time the readyState changes, the onreadystatechange function will be executed. Here are the possible values for the readyState property:<br />
State Description<br />
0 The request is not initialized<br />
1 The request has been set up<br />
2 The request has been sent<br />
3 The request is in process<br />
4 The request is complete</p>
<p>And status is the status of the HTTP Request, like 500 Internal Server Error, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found etc. 200 means no error.</p>
<p class="textBoldBlue">4. Get the response</p>
<p>The response will be as string or as XML. The data sent back from the server can be retrieved with the responseText property as string. Use responseXML for getting the response as XML.</p>
<p><span class="textBoldBlue">5. Use the response on your web pag</span>e</p>
<p>You can use the response you got from the XMLHttpRequest in your web page/application. You can either set a value of a text field or use the returned HTML from the web request as innerHTML for a &lt;div&gt;&lt;/div&gt; tag or &lt;span&gt;&lt;/span&gt; tag (See below for the implementation of this)</p>
<p><em><strong>Using AJAX with PHP</strong></em></p>
<p>I usually place all the AJAX related functions in one JavaScript (ajax.js), and later add the JavaScript in my PHP pages. My ajax.js looks like below.</p>
<p class="textCode">function createRequestObject(){</p>
<p>var req;</p>
<p>if(window.XMLHttpRequest){<br />
//For Firefox, Safari, Opera<br />
req = new XMLHttpRequest();<br />
}<br />
else if(window.ActiveXObject){<br />
//For IE 5+<br />
req = new ActiveXObject(&#8220;Microsoft.XMLHTTP&#8221;);<br />
}<br />
else{<br />
//Error for an old browser<br />
alert(&#8216;Your browser is not IE 5 or higher, or Firefox or Safari or Opera&#8217;);<br />
}</p>
<p>return req;<br />
}</p>
<p class="textCode">//Make the XMLHttpRequest Object<br />
var http = createRequestObject();</p>
<p class="textCode">function sendRequest(method, url){<br />
if(method == &#8216;get&#8217; || method == &#8216;GET&#8217;){<br />
http.open(method,url,true);<br />
http.onreadystatechange = handleResponse;<br />
http.send(null);<br />
}<br />
}</p>
<p class="textCode">function handleResponse(){<br />
if(http.readyState == 4 &amp;&amp; http.status == 200){<br />
var response = http.responseText;<br />
if(response){<br />
document.getElementById(&#8220;ajax_res&#8221;).innerHTML = response;<br />
}<br />
}<br />
}</p>
<p>Now I add a &lt;script&gt;&lt;/script&gt; tag in my PHP pages like following to access the JavaScript functions.</p>
<p><img src="http://www.ajaxmatters.com/articles/php/www.ajaxmatters.com/images/phpjava_intro1.gif" alt="" /></p>
<p>Then I create a function called sendReq() as shown above for preparing the URL to the PHP page to get some data from the database. If you look into the ajax.js, you will see that I’m assigning the output of the PHP page to a &lt;div&gt; tags innerHTML. My div tag has the id=’ajax_res’.</p>
<p class="textCode">&lt;div align=&#8221;center&#8221; class=&#8221;black&#8221; id=&#8221;ajax_res&#8221;&gt;<br />
&lt;img src=&#8221;wt_bg.jpg&#8221;&gt;<br />
&lt;/div&gt;</p>
<p>After calling the sendReq function with a value of ‘success’, it will connect to the server for sending a request to the URL get_lcm.php?status=success, then get the data from the database using the value ‘success’, and set the innerHTML attribute of the div tag whose id is ‘ajax_res’ according to the response. Initially my div tag shows an image, but after AJAX responds successfully this image will be replaced with the response. You can also get the response as the value of an input text.</p>
<p>My get_lcm.php looks like this.</p>
<p class="textCode">&lt;?php<br />
include_once(&#8220;create_table.php&#8221;);</p>
<p class="textCode">if(!empty($status)){<br />
echo &#8220;&lt;strong&gt;Search Result for Status: &#8220;.$status.&#8221;&lt;/strong&gt;&lt;br&gt;&lt;br&gt;&#8221;;</p>
<p class="textCode">$ct = new createtable(&#8220;select * from lcm where state=$status&#8221;);</p>
<p class="textCode">$ct-&gt;table_viewer();<br />
}<br />
?&gt;</p>
<p>I used one of my PHP classes ‘create_table.php’ for creating a table from SQL queries. ‘create_table.php’ has a function, table_viewer(), to print the SQL output as a HTML table. I will discuss about this class and some other data abstraction classes I used in some later articles, if necessary.</p>
<p>I had the following HTML code for calling the AJAX function using the sendReq() as described earlier.</p>
<p class="textCode">&lt;a class=&#8221;none&#8221; href=&#8221;#&#8221; onClick=&#8221;sendReq(1)&#8221;&gt;ACTIVE&lt;/a&gt;</p>
<p>If a user clicks the above hyperlink, then the JavaScript function sendReq is invoked using the value of status equal to 1. After that the webpage with URL get_lcm.php?status=1 will be invoked. This PHP will get the information from database and shows the result as table. This result will then be displayed within the &lt;div&gt; tag.</p>
<p>Using AJAX from PHP is very easy as described here. All you need is the JavaScript functions for sending the XMLHttpRequest and then handle the Http Response. It will simplify development is you place all your AJAX related code in a single JavaScript file and reference it from anywhere you need AJAX.</p>
<p>There is another way of getting the same result from PHP without using the XMLHttpRequest object. But I personally do not like the concept, because it is missing one of the main ingredients of Asynchronous JavaScript And XML (AJAX), XML. This concept is good for the old browsers with no supports for XMLHttpRequest object, but as all the newer versions are supporting XMLHttpRequest object you can use AJAX for the common browsers.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathayi.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathayi.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mathayi.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mathayi.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mathayi.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mathayi.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mathayi.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mathayi.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mathayi.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mathayi.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mathayi.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mathayi.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mathayi.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mathayi.wordpress.com/32/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=32&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathayi.wordpress.com/2009/01/19/getting-started-with-ajax-using-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6b6115bcb8fd0e144662eb67264cc416?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathayi</media:title>
		</media:content>

		<media:content url="http://www.ajaxmatters.com/articles/php/www.ajaxmatters.com/images/phpjava_intro1.gif" medium="image" />
	</item>
		<item>
		<title>Design Patterns in PHP</title>
		<link>http://mathayi.wordpress.com/2009/01/19/design-patterns-in-php/</link>
		<comments>http://mathayi.wordpress.com/2009/01/19/design-patterns-in-php/#comments</comments>
		<pubDate>Mon, 19 Jan 2009 10:06:28 +0000</pubDate>
		<dc:creator>mathayi</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://mathayi.wordpress.com/?p=28</guid>
		<description><![CDATA[v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} &#60;!&#8211; /* Font Definitions */ @font-face {font-family:Courier; panose-1:2 7 4 9 2 2 5 2 4 4; mso-font-alt:&#8221;Courier New&#8221;; mso-font-charset:0; mso-generic-font-family:modern; mso-font-format:other; mso-font-pitch:fixed; mso-font-signature:3 0 0 0 1 0;} @font-face {font-family:Verdana; panose-1:2 11 6 4 3 5 4 4 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:536871559 0 0 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=28&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><!--[if !mso]&gt;--><br />
v\:* {behavior:url(#default#VML);}<br />
o\:* {behavior:url(#default#VML);}<br />
w\:* {behavior:url(#default#VML);}<br />
.shape {behavior:url(#default#VML);}<br />
 <!--[if gte mso 9]&gt;  Normal 0   false false false        MicrosoftInternetExplorer4  &lt;![endif]--><!--[if gte mso 9]&gt;   &lt;![endif]--> &lt;!&#8211;  /* Font Definitions */  @font-face 	{font-family:Courier; 	panose-1:2 7 4 9 2 2 5 2 4 4; 	mso-font-alt:&#8221;Courier New&#8221;; 	mso-font-charset:0; 	mso-generic-font-family:modern; 	mso-font-format:other; 	mso-font-pitch:fixed; 	mso-font-signature:3 0 0 0 1 0;} @font-face 	{font-family:Verdana; 	panose-1:2 11 6 4 3 5 4 4 2 4; 	mso-font-charset:0; 	mso-generic-font-family:swiss; 	mso-font-pitch:variable; 	mso-font-signature:536871559 0 0 0 415 0;} @font-face 	{font-family:&#8221;Lucida Console&#8221;; 	panose-1:2 11 6 9 4 5 4 2 2 4; 	mso-font-charset:0; 	mso-generic-font-family:modern; 	mso-font-pitch:fixed; 	mso-font-signature:-2147482993 6144 0 0 31 0;}  /* Style Definitions */  p.MsoNormal, li.MsoNormal, div.MsoNormal 	{mso-style-parent:&#8221;"; 	margin:0in; 	margin-bottom:.0001pt; 	mso-pagination:widow-orphan; 	font-size:12.0pt; 	font-family:&#8221;Times New Roman&#8221;; 	mso-fareast-font-family:&#8221;Times New Roman&#8221;;} h1 	{mso-margin-top-alt:auto; 	margin-right:0in; 	mso-margin-bottom-alt:auto; 	margin-left:0in; 	mso-pagination:widow-orphan; 	mso-outline-level:1; 	font-size:16.5pt; 	font-family:Arial; 	color:black; 	font-weight:bold;} p 	{mso-margin-top-alt:auto; 	margin-right:0in; 	mso-margin-bottom-alt:auto; 	margin-left:0in; 	mso-pagination:widow-orphan; 	font-size:12.0pt; 	font-family:&#8221;Times New Roman&#8221;; 	mso-fareast-font-family:&#8221;Times New Roman&#8221;;} code 	{mso-ansi-font-size:11.0pt; 	mso-bidi-font-size:11.0pt; 	font-family:Courier; 	mso-ascii-font-family:Courier; 	mso-fareast-font-family:&#8221;Times New Roman&#8221;; 	mso-hansi-font-family:Courier; 	mso-bidi-font-family:&#8221;Courier New&#8221;;} pre 	{margin:0in; 	margin-bottom:.0001pt; 	mso-pagination:widow-orphan; 	tab-stops:45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt; 	font-size:10.0pt; 	font-family:&#8221;Courier New&#8221;; 	mso-fareast-font-family:&#8221;Times New Roman&#8221;;} span.atitle1 	{mso-style-name:atitle1; 	mso-ansi-font-size:19.0pt; 	mso-bidi-font-size:19.0pt; 	font-family:Arial; 	mso-ascii-font-family:Arial; 	mso-hansi-font-family:Arial; 	mso-bidi-font-family:Arial; 	font-weight:bold;} @page Section1 	{size:8.5in 11.0in; 	margin:1.0in 1.25in 1.0in 1.25in; 	mso-header-margin:.5in; 	mso-footer-margin:.5in; 	mso-paper-source:0;} div.Section1 	{page:Section1;}  /* List Definitions */  @list l0 	{mso-list-id:1565407075; 	mso-list-template-ids:26618656;} @list l0:level1 	{mso-level-tab-stop:.5in; 	mso-level-number-position:left; 	text-indent:-.25in;} ol 	{margin-bottom:0in;} ul 	{margin-bottom:0in;} &#8211;&gt; <!--[if gte mso 10]&gt;--><br />
 /* Style Definitions */<br />
 table.MsoNormalTable<br />
	{mso-style-name:&#8221;Table Normal&#8221;;<br />
	mso-tstyle-rowband-size:0;<br />
	mso-tstyle-colband-size:0;<br />
	mso-style-noshow:yes;<br />
	mso-style-parent:&#8221;";<br />
	mso-padding-alt:0in 5.4pt 0in 5.4pt;<br />
	mso-para-margin:0in;<br />
	mso-para-margin-bottom:.0001pt;<br />
	mso-pagination:widow-orphan;<br />
	font-size:10.0pt;<br />
	font-family:&#8221;Times New Roman&#8221;;<br />
	mso-ansi-language:#0400;<br />
	mso-fareast-language:#0400;<br />
	mso-bidi-language:#0400;}</p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Design patterns were introduced to the software community in <em>Design Patterns</em>, by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (colloquially known as the &#8220;gang of four&#8221;). The core concept behind design patterns, presented in the introduction, was simple. Over their years of developing software, Gamma et al found certain patterns of solid design emerging, just as architects designing houses and buildings can develop templates for where a bathroom should be located or how a kitchen should be configured. Having those templates, or <em>design patterns</em>, means they can design better buildings more quickly. The same applies to software.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Design patterns not only present useful ways for developing robust software faster but also provide a way of encapsulating large ideas in friendly terms. For example, you can say you&#8217;re writing a messaging system to provide for loose coupling, or you can say you&#8217;re writing an <em>observer</em>, which is the name of that pattern.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">It&#8217;s difficult to demonstrate the value of patterns using small examples. They often look like overkill because they really come into play in large code bases. This article can&#8217;t show huge applications, so you need to think about ways to apply the principles of the example &#8212; and not necessarily this exact code &#8212; in your larger applications. That&#8217;s not to say that you shouldn&#8217;t use patterns in small applications. Most good applications start small and become big, so there is no reason not to start with solid coding practices like these.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Now that you have a sense of what design patterns are and why they&#8217;re useful, it&#8217;s time to jump into five common patterns for PHP V5.</span></p>
<p class="MsoNormal"><a name="N10076"><span class="atitle1"><span style="font-size:13.5pt;color:black;">The factory pattern</span></span></a><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Many of the design patterns in the original <em>Design Patterns</em> book encourage <em>loose coupling</em>. To understand this concept, it&#8217;s easiest to talk about a struggle that many developers go through in large systems. The problem occurs when you change one piece of code and watch as a cascade of breakage happens in other parts of the system &#8212; parts you thought were completely unrelated.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The problem is <em>tight coupling</em>. Functions and classes in one part of the system rely too heavily on behaviors and structures in other functions and classes in other parts of the system. You need a set of patterns that lets these classes talk with each other, but you don&#8217;t want to tie them together so heavily that they become interlocked.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">In large systems, lots of code relies on a few key classes. Difficulties can arise when you need to change those classes. For example, suppose you have a </span><code><span style="font-size:7.5pt;color:black;">User</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> class that reads from a file. You want to change it to a different class that reads from the database, but all the code references the original class that reads from a file. This is where the factory pattern comes in handy.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The <em>factory pattern</em> is a class that has some methods that create objects for you. Instead of using </span><code><span style="font-size:7.5pt;color:black;">new</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> directly, you use the factory class to create objects. That way, if you want to change the types of objects created, you can change just the factory. All the code that uses the factory changes automatically.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Listing 1 shows an example of a factory class. The server side of the equation comes in two pieces: the database, and a set of PHP pages that let you add feeds, request the list of feeds, and get the article associated with a particular feed.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="listing1"><strong>Listing 1. Factory1.php</strong></a></span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;"><span>                </span></span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">&lt;?php</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">interface IUser</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>function getName();</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class User implements IUser</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function __construct( $id ) { }</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function getName()</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>return "Jack";</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class UserFactory</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public static function Create( $id )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>return new User( $id );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$uo = UserFactory::Create( 1 );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">echo( $uo-&gt;getName()."\n" );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">?&gt;</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">An interface called </span><code><span style="font-size:7.5pt;color:black;">IUser</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> defines what a user object should do. The implementation of </span><code><span style="font-size:7.5pt;color:black;">IUser</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> is called </span><code><span style="font-size:7.5pt;color:black;">User</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;">, and a factory class called </span><code><span style="font-size:7.5pt;color:black;">UserFactory</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> creates </span><code><span style="font-size:7.5pt;color:black;">IUser</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> objects. This relationship is shown as UML in Figure 1.</span></p>
<p class="MsoNormal" style="margin-bottom:12pt;"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="fig1"><strong>Figure 1. The factory class and its related IUser interface and user class</strong></a><br />
<!--[if gte vml 1]&gt;                    &lt;![endif]--><!--[if !vml]--><img src="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image001.gif" alt="The factory class and its related IUser interface and user class" width="221" height="86" /><!--[endif]--></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">If you run this code on the command line using the </span><code><span style="font-size:7.5pt;color:black;">php</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> interpreter, you get this result:</span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;">% php factory1.php </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">Jack</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">%</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The test code asks the factory for a </span><code><span style="font-size:7.5pt;color:black;">User</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> object and prints the result of the </span><code><span style="font-size:7.5pt;color:black;">getName</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> method.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">A variation of the factory pattern uses factory methods. These public static methods in the class construct objects of that type. This approach is useful when creating an object of this type is nontrivial. For example, suppose you need to first create the object and then set many attributes. This version of the factory pattern encapsulates that process in a single location so that the complex initialization code isn&#8217;t copied and pasted all over the code base.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Listing 2 shows an example of using factory methods.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="listing2"><strong>Listing 2. Factory2.php</strong></a></span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;"><span>                </span></span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">&lt;?php</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">interface IUser</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>function getName();</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class User implements IUser</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public static function Load( $id ) </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>        </span>return new User( $id );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public static function Create( ) </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>        </span>return new User( null );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function __construct( $id ) { }</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function getName()</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>return "Jack";</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$uo = User::Load( 1 );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">echo( $uo-&gt;getName()."\n" );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">?&gt;</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">This code is much simpler. It has only one interface, </span><code><span style="font-size:7.5pt;color:black;">IUser</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;">, and one class called </span><code><span style="font-size:7.5pt;color:black;">User</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> that implements the interface. The </span><code><span style="font-size:7.5pt;color:black;">User</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> class has two static methods that create the object. This relationship is shown in UML in Figure 2.</span></p>
<p class="MsoNormal" style="margin-bottom:12pt;"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="fig2"><strong>Figure 2. The IUser interface and the user class with factory methods</strong></a><br />
<!--[if gte vml 1]&gt;  &lt;![endif]--><!--[if !vml]--><img src="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image002.gif" alt="The IUser interface and the user class with factory methods" width="95" height="113" /><!--[endif]--></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Running the script on the command line yields the same result as the code in Listing 1, as shown here:</span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;">% php factory2.php </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">Jack</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">%</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">As stated, sometimes such patterns can seem like overkill in small situations. Nevertheless, it&#8217;s still good to learn solid coding forms like these for use in any size of project.</span></p>
<p class="MsoNormal"><a name="N10124"><span class="atitle1"><span style="font-size:13.5pt;color:black;">The singleton pattern</span></span></a><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Some application resources are <em>exclusive</em> in that there is one and only one of this type of resource. For example, the connection to a database through the database handle is exclusive. You want to share the database handle in an application because it&#8217;s an overhead to keep opening and closing connections, particularly during a single page fetch.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The singleton pattern covers this need. An object is a <em>singleton</em> if the application can include one and only one of that object at a time. The code in Listing 3 shows a database connection singleton in PHP V5.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="listing3"><strong>Listing 3. Singleton.php</strong></a></span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;"><span>                </span></span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">&lt;?php</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">require_once("DB.php");</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class DatabaseConnection</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public static function get()</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>static $db = null;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>if ( $db == null )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>      </span>$db = new DatabaseConnection();</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>return $db;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>private $_handle = null;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>private function __construct()</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>$dsn = 'mysql://root:password@localhost/photos';</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>$this-&gt;_handle =&amp; DB::Connect( $dsn, array() );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span></span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function handle()</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>return $this-&gt;_handle;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">print( "Handle = ".DatabaseConnection::get()-&gt;handle()."\n" );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">print( "Handle = ".DatabaseConnection::get()-&gt;handle()."\n" );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">?&gt;</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">This code shows a single class called </span><code><span style="font-size:7.5pt;color:black;">DatabaseConnection</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;">. You can&#8217;t create your own </span><code><span style="font-size:7.5pt;color:black;">DatabaseConnection</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> because the constructor is private. But you can get the one and only one </span><code><span style="font-size:7.5pt;color:black;">DatabaseConnection</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> object using the static </span><code><span style="font-size:7.5pt;color:black;">get</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> method. The UML for this code is shown in Figure 3.</span></p>
<p class="MsoNormal" style="margin-bottom:12pt;"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="fig3"><strong>Figure 3. The database connection singleton</strong></a><br />
<!--[if gte vml 1]&gt;  &lt;![endif]--><!--[if !vml]--><img src="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image003.gif" alt="The database connection singleton" width="165" height="41" /><!--[endif]--></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The proof in the pudding is that the database handle returned by the </span><code><span style="font-size:7.5pt;color:black;">handle</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> method is the same between two calls. You can see this by running the code on the command line.</span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;">% php singleton.php </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">Handle = Object id #3</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">Handle = Object id #3</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">%</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The two handles returned are the same object. If you use the database connection singleton across the application, you reuse the same handle everywhere.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">You could use a global variable to store the database handle, but that approach only works for small applications. In larger applications, avoid globals, and go with objects and methods to get access to resources.</span></p>
<p class="MsoNormal"><a name="N10177"><span class="atitle1"><span style="font-size:13.5pt;color:black;">The observer pattern</span></span></a><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The observer pattern gives you another way to avoid tight coupling between components. This pattern is simple: One object makes itself observable by adding a method that allows another object, the <em>observer</em>, to register itself. When the observable object changes, it sends a message to the registered observers. What those observers do with that information isn&#8217;t relevant or important to the observable object. The result is a way for objects to talk with each other without necessarily understanding why.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">A simple example is a list of users in a system. The code in Listing 4 shows a user list that sends out a message when users are added. This list is watched by a logging observer that puts out a message when a user is added.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="listing4"><strong>Listing 4. Observer.php</strong></a></span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;"><span>                </span></span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">&lt;?php</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">interface IObserver</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>function onChanged( $sender, $args );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">interface IObservable</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>function addObserver( $observer );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class UserList implements IObservable</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>private $_observers = array();</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function addCustomer( $name )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>foreach( $this-&gt;_observers as $obs )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>      </span>$obs-&gt;onChanged( $this, $name );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function addObserver( $observer )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>$this-&gt;_observers []= $observer;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class UserListLogger implements IObserver</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function onChanged( $sender, $args )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>echo( "'$args' added to user list\n" );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$ul = new UserList();</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$ul-&gt;addObserver( new UserListLogger() );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$ul-&gt;addCustomer( "Jack" );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">?&gt;</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">This code defines four elements: two interfaces and two classes. The </span><code><span style="font-size:7.5pt;color:black;">IObservable</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> interface defines an object that can be observed, and the </span><code><span style="font-size:7.5pt;color:black;">UserList</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> implements that interface to register itself as observable. The </span><code><span style="font-size:7.5pt;color:black;">IObserver</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> list defines what it takes to be an observer, and the </span><code><span style="font-size:7.5pt;color:black;">UserListLogger</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> implements that </span><code><span style="font-size:7.5pt;color:black;">IObserver</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> interface. This is shown in the UML in Figure 4.</span></p>
<p class="MsoNormal" style="margin-bottom:12pt;"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="fig4"><strong>Figure 4. The observable user list and the user list event logger</strong></a><br />
<!--[if gte vml 1]&gt;  &lt;![endif]--><!--[if !vml]--><img src="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image004.gif" alt="The observable user list and the user list event logger" width="414" height="99" /><!--[endif]--></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">If you run this on the command line, you see this output:</span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;">% php observer.php </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">'Jack' added to user list</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">%</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The test code creates a </span><code><span style="font-size:7.5pt;color:black;">UserList</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> and adds the </span><code><span style="font-size:7.5pt;color:black;">UserListLogger</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> observer to it. Then the code adds a customer, and the </span><code><span style="font-size:7.5pt;color:black;">UserListLogger</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> is notified of that change.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">It&#8217;s critical to realize that the </span><code><span style="font-size:7.5pt;color:black;">UserList</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> doesn&#8217;t know what the logger is going to do. There could be one or more listeners that do other things. For example, you may have an observer that sends a message to the new user, welcoming him to the system. The value of this approach is that the </span><code><span style="font-size:7.5pt;color:black;">UserList</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> is ignorant of all the objects depending on it; it focuses on its job of maintaining the user list and sending out messages when the list changes.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">This pattern isn&#8217;t limited to objects in memory. It&#8217;s the underpinning of the database-driven message queuing systems used in larger applications.</span></p>
<p class="MsoNormal"><a name="N101DE"><span class="atitle1"><span style="font-size:13.5pt;color:black;">The chain-of-command pattern</span></span></a><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Building on the loose-coupling theme, the <em>chain-of-command</em> pattern routes a message, command, request, or whatever you like through a set of handlers. Each handler decides for itself whether it can handle the request. If it can, the request is handled, and the process stops. You can add or remove handlers from the system without influencing other handlers. Listing 5 shows an example of this pattern.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="listing5"><strong>Listing 5. Chain.php</strong></a></span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;"><span>                </span></span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">&lt;?php</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">interface ICommand</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>function onCommand( $name, $args );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class CommandChain</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>private $_commands = array();</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function addCommand( $cmd )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>$this-&gt;_commands []= $cmd;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function runCommand( $name, $args )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>foreach( $this-&gt;_commands as $cmd )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>      </span>if ( $cmd-&gt;onCommand( $name, $args ) )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>        </span>return;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class UserCommand implements ICommand</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function onCommand( $name, $args )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>if ( $name != 'addUser' ) return false;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>echo( "UserCommand handling 'addUser'\n" );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>return true;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class MailCommand implements ICommand</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function onCommand( $name, $args )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>if ( $name != 'mail' ) return false;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>echo( "MailCommand handling 'mail'\n" );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>return true;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$cc = new CommandChain();</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$cc-&gt;addCommand( new UserCommand() );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$cc-&gt;addCommand( new MailCommand() );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$cc-&gt;runCommand( 'addUser', null );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$cc-&gt;runCommand( 'mail', null );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">?&gt;</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">This code defines a </span><code><span style="font-size:7.5pt;color:black;">CommandChain</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> class that maintains a list of </span><code><span style="font-size:7.5pt;color:black;">ICommand</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> objects. Two classes implement the </span><code><span style="font-size:7.5pt;color:black;">ICommand</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> interface &#8212; one that responds to requests for mail and another that responds to adding users. The UML is shows in Figure 5.</span></p>
<p class="MsoNormal" style="margin-bottom:12pt;"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="fig5"><strong>Figure 5. The command chain and its related commands</strong></a><br />
<!--[if gte vml 1]&gt;  &lt;![endif]--><!--[if !vml]--><img src="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image005.gif" alt="The command chain and its related commands" width="359" height="121" /><!--[endif]--></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">If you run the script, which contains some test code, you see the following output:</span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;">% php chain.php </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">UserCommand handling 'addUser'</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">MailCommand handling 'mail'</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">%</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The code first creates a </span><code><span style="font-size:7.5pt;color:black;">CommandChain</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> object and adds instances of the two command objects to it. It then runs two commands to see who responds to those commands. If the name of the command matches either </span><code><span style="font-size:7.5pt;color:black;">UserCommand</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> or </span><code><span style="font-size:7.5pt;color:black;">MailCommand</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;">, the code falls through and nothing happens.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The chain-of-command pattern can be valuable in creating an extensible architecture for processing requests, which can be applied to many problems. </span></p>
<p class="MsoNormal"><a name="N1022F"><span class="atitle1"><span style="font-size:13.5pt;color:black;">The strategy pattern</span></span></a><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The last design pattern we will cover is the <em>strategy</em> pattern. In this pattern, algorithms are extracted from complex classes so they can be replaced easily. For example, the strategy pattern is an option if you want to change the way pages are ranked in a search engine. Think about a search engine in several parts &#8212; one that iterates through the pages, one that ranks each page, and another that orders the results based on the rank. In a complex example, all those parts would be in the same class. Using the strategy pattern, you take the ranking portion and put it into another class so you can change how pages are ranked without interfering with the rest of the search engine code.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">As a simpler example, Listing 6 shows a user list class that provides a method for finding a set of users based on a plug-and-play set of strategies. </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="listing6"><strong>Listing 6. Strategy.php</strong></a></span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;"><span>                </span></span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">&lt;?php</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">interface IStrategy</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>function filter( $record );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class FindAfterStrategy implements IStrategy</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>private $_name;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function __construct( $name )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>$this-&gt;_name = $name;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function filter( $record )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>return strcmp( $this-&gt;_name, $record ) &lt;= 0;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class RandomStrategy implements IStrategy</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function filter( $record )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>return rand( 0, 1 ) &gt;= 0.5;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">class UserList</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>private $_list = array();</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function __construct( $names )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>if ( $names != null )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>      </span>foreach( $names as $name )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>      </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>        </span>$this-&gt;_list []= $name;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>      </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function add( $name )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>$this-&gt;_list []= $name;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>public function find( $filter )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>$recs = array();</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>foreach( $this-&gt;_list as $user )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>{</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>      </span>if ( $filter-&gt;filter( $user ) )</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>        </span>$recs []= $user;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>return $recs;</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>  </span>}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">}</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$ul = new UserList( array( "Andy", "Jack", "Lori", "Megan" ) );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$f1 = $ul-&gt;find( new FindAfterStrategy( "J" ) );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">print_r( $f1 );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"> </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">$f2 = $ul-&gt;find( new RandomStrategy() );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">print_r( $f2 );</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">?&gt;</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The UML for this code is shown in Figure 6.</span></p>
<p class="MsoNormal" style="margin-bottom:12pt;"><span style="font-size:8.5pt;font-family:Verdana;color:black;"><br />
<a name="fig6"><strong>Figure 6. The user list and the strategies for selecting users</strong></a><br />
<!--[if gte vml 1]&gt;  &lt;![endif]--><!--[if !vml]--><img src="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image006.gif" alt="The user list and the strategies for selecting users" width="309" height="138" /><!--[endif]--></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The </span><code><span style="font-size:7.5pt;color:black;">UserList</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> class is a wrapper around an array of names. It implements a </span><code><span style="font-size:7.5pt;color:black;">find</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> method that takes one of several strategies for selecting a subset of those names. Those strategies are defined by the </span><code><span style="font-size:7.5pt;color:black;">IStrategy</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;"> interface, which has two implementations: One chooses users randomly and the other chooses all the names after a specified name. When you run the test code, you get the following output:</span></p>
<table class="MsoNormalTable" style="width:100%;" border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td style="border:1pt solid #cccccc;background:#eeeeee none repeat scroll 0 0;padding:3.75pt;">
<pre><span style="font-size:8.5pt;font-family:&quot;color:black;">% php strategy.php </span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">Array</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">(</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>[0] =&gt; Jack</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>[1] =&gt; Lori</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>[2] =&gt; Megan</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">)</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">Array</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">(</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>[0] =&gt; Andy</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;"><span>    </span>[1] =&gt; Megan</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">)</span>
<span style="font-size:8.5pt;font-family:&quot;color:black;">%</span></pre>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The test code runs the same user lists against two strategies and shows the results. In the first case, the strategy looks for any name that sorts after </span><code><span style="font-size:7.5pt;color:black;">J</span></code><span style="font-size:8.5pt;font-family:Verdana;color:black;">, so you get Jack, Lori, and Megan. The second strategy picks names randomly and yields different results every time. In this case, the results are Andy and Megan.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The strategy pattern is great for complex data-management systems or data-processing systems that need a lot of flexibility in how data is filtered, searched, or processed.</span></p>
<p class="MsoNormal"><a name="N1027B"><span class="atitle1"><span style="font-size:13.5pt;color:black;">Conclusions</span></span></a><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<div style="border:medium medium 1pt none none solid 0 0 windowtext;padding:0 0 1pt;">
<p class="MsoNormal" style="border:medium none;padding:0;"><span style="font-size:8.5pt;font-family:Verdana;color:black;">These are just a few of the most common design patterns used in PHP applications. Many more are demonstrated in the <em>Design Patterns</em> book. Don&#8217;t be put off by the mystique of architecture. Patterns are great ideas you can use in any programming language and at any skill level.</span></p>
</div>
<p class="MsoNormal"><strong><span style="font-size:8.5pt;font-family:Verdana;color:black;">Design Patterns in PHP &#8211; Factory Method and Abstract Factory</span></strong></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">(Page 1 of 5 )</p>
<p>Normally, in object oriented programming, object creation is not difficult. But what if your object needs to be created based on different conditions or other matters of context? Then you will spend hours in debugging and updating&#8211;unless you know about design patterns. David Fells explains how they work, and uses the creation of a maze to illustrate his points. </span></p>
<p class="MsoNormal"><strong><span style="font-size:8.5pt;font-family:Verdana;color:black;">Overview</span></strong><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">In object oriented programming, object creation &#8211; also known as instantiation &#8211; is an implied requirement. Objects must at some point be created for use. Obviously, creating objects is not a difficult task and most languages, PHP included, have simple and intuitive syntax for doing so. </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">When developing larger, more complex systems though, object creation can become difficult. There are situations where different objects may need to be created based on different conditions or based on the context of the object creating it. Creating objects of concrete types explicitly in code can make these situations a nightmare when it comes time to make revisions and additions. When a new class is introduced, you get to follow a trail of code and commence the hours of debugging that will inevitably follow such an endeavor. This is where design patterns come in.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">This article will discuss the usage of Factory Method [DP107] and Abstract Factory [DP87] as they pertain to developing applications in PHP using object oriented programming techniques.</span></p>
<p class="MsoNormal"><strong><span style="font-size:8.5pt;font-family:Verdana;color:black;">Design Patterns in PHP &#8211; Factory Method and Abstract Factory &#8211; Factory Method</span></strong></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The first pattern used to simplify object instantiation is the Factory Method pattern. The Factory Method pattern defines an interface for object creation but defers the actual instantiation to subclasses. Take, for example, an application that processes Electronic Funds Transfers (ETFs). There are numerous types of ETFs including virtual check, credit card, wire transfer and so on. Using a non-pattern based approach, the application code requesting an ETF object would need to know precisely what subclass of ETF is needed, and it would need to know the context in which that type of ETF is requested. We would end up with code looking something like this:</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">switch ($etfType) {<br />
case ETF_VIRTUALCHECK :<br />
$etf = new VirtualCheck();<br />
$etf-&gt;processCheck();<br />
break;<br />
case ETF_CREDITCARD :<br />
$etf = new CreditCard();<br />
$etf-&gt;chargeCard();<br />
break;<br />
case ETF_WIRETRANSFER :<br />
$etf = new WireTransfer();<br />
$etf-&gt;chargeCard();<br />
break;<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Any time we want to add another ETF, we would have to manually update this switch statement anywhere it appeared. We would also have to update any other conditional code that appears. The CreditCard class hinted at above offers the same problem as the ETF itself in that each credit card type (VISA, MasterCard, AMEX) has its own validation scheme and many types have different numerical formats. We would see a similar switch statement to determine what type of credit card we were dealing with either in the CreditCard class constructor or in the switch statement above creates the CreditCard object.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">By implementing the Factory Method, we code our application so it only expects a class that conforms to an interface &#8211; that is, it has certain methods and properties that can be used to submit an ETF and check whether it failed or succeeded. This promotes loose coupling in the application because you are not binding a concrete subclass to application code. The result is a great increase in flexibility and maintainability. It is easy to add new ETF subclasses and implement them because you are not hard coding the application to expect a specific subclass, just a class with a specific interface. Look at this example.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class ETF {<br />
var $data;<br />
function ETF($data) {<br />
$this-&gt;data = $data;<br />
}<br />
function process() {}<br />
function getResult() {}<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class VirtualCheck extends ETF {}<br />
class WireTransfer extends ETF {}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class ETFFactory {<br />
function createETF($data) {<br />
switch ($data['etfType']) {<br />
case ETF_VIRTUALCHECK :<br />
return new VirtualCheck($data);;<br />
case ETF_WIRETRANSFER :<br />
return new WireTransfer($data);<br />
default :<br />
return new ETF($data);<br />
}<br />
}<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">$data = $_POST;<br />
$etf = ETFFactory::createETF($data);<br />
$etf-&gt;process();</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">This is a crude implementation but the intent should be clear. Assume the contents of $_POST represent everything you need for the type of ETF that is happening, including a &#8216;etfType&#8217; that says what sort of ETF you are using. This would come from the user making a selection in a form and filling out the correct information. This implementation provides numerous advantages over the first.</span></p>
<p class="MsoNormal" style="margin-left:.5in;text-indent:-.25in;"><!--[if !supportLists]--><span style="font-size:8.5pt;font-family:Verdana;color:black;"><span>1.<span style="font-family:&quot;font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;"> </span></span></span><!--[endif]--><span style="font-size:8.5pt;font-family:Verdana;color:black;">Data validation can be left entirely to the subclasses and occur without interaction from calling code.<br />
<!--[if !supportLineBreakNewLine]--><br />
<!--[endif]--></span></p>
<p class="MsoNormal" style="margin-left:.5in;text-indent:-.25in;"><!--[if !supportLists]--><span style="font-size:8.5pt;font-family:Verdana;color:black;"><span>2.<span style="font-family:&quot;font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;"> </span></span></span><!--[endif]--><span style="font-size:8.5pt;font-family:Verdana;color:black;">Calling code only needs to know of one way to get an ETF object.<br />
<!--[if !supportLineBreakNewLine]--><br />
<!--[endif]--></span></p>
<p class="MsoNormal" style="margin-left:.5in;text-indent:-.25in;"><!--[if !supportLists]--><span style="font-size:8.5pt;font-family:Verdana;color:black;"><span>3.<span style="font-family:&quot;font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;"> </span></span></span><!--[endif]--><span style="font-size:8.5pt;font-family:Verdana;color:black;">Creation logic is encapsulated &#8211; the ETFFactory decides what concrete class to create based on the contents of $data['etfType']. Calling application code knows nothing of concrete subclasses of ETF.<br />
<!--[if !supportLineBreakNewLine]--><br />
<!--[endif]--></span></p>
<p class="MsoNormal" style="margin-left:.5in;text-indent:-.25in;"><!--[if !supportLists]--><span style="font-size:8.5pt;font-family:Verdana;color:black;"><span>4.<span style="font-family:&quot;font-style:normal;font-variant:normal;font-weight:normal;font-size:7pt;line-height:normal;"> </span></span></span><!--[endif]--><span style="font-size:8.5pt;font-family:Verdana;color:black;">If special measures need to be taken, such as creating a specific type of credit card object, this can take place in one location without the calling application code being involved.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Using this approach consolidates creation logic in a single class &#8211; ETFFactory. This eliminates duplication in code when an object is created in multiple locations. With the first method, if a class name is changed or a new ETF class is added, we have to modify the ETF creation code everywhere it appears in our application. With the Factory Method implementation, this is not the case. Our calling application code knows of only ETFFactory and ETF. Subclasses of ETF provide the required specialized behaviors to process themselves in the appropriate way but the calling code needs only to use the process() method.</span></p>
<p class="MsoNormal"><strong><span style="font-size:8.5pt;font-family:Verdana;color:black;">Design Patterns in PHP &#8211; Factory Method and Abstract Factory &#8211; Abstract Factory</span></strong></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes [DP87]. This pattern takes the abstraction displayed in the example above to the next level by providing a common factory interface for a given family of objects. The code that actually uses the factory to create objects only expects an object that conforms to the interface of the abstract factory and does not know any details about concrete factory classes.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Using the example from Design Patterns, consider a game that creates a maze. We have a method that knows what to do to create a maze and it will instantiate all the objects we need to construct the maze &#8211; components such as rooms, doors and walls. The example below defines the classes involved &#8211; method code is left out deliberately since it is not important to this discussion.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class MapSite {<br />
function enter() {}<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">define(&#8216;North&#8217;, 0);<br />
define(&#8216;East&#8217;, 1);<br />
define(&#8216;South&#8217;, 2);<br />
define(&#8216;West&#8217;, 3);</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class Room extends MapSite {<br />
var $mapSite = array();<br />
var $roomNumber;</p>
<p>function Room($roomNumber) {}<br />
function getSide($direction) {}<br />
function setSide($direction, $mapSite) {}<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class Wall extends MapSite {<br />
function Wall() {}<br />
function enter() {}<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class Door extends MapSite {<br />
var $room1;<br />
var $room2;<br />
var $isOpen;</p>
<p>function Door() {}<br />
function enter() {}<br />
function otherSideFrom($room);<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class Maze {<br />
function Maze() {}<br />
function addRoom($room) {}<br />
// Etc…<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class MazeGame {<br />
function createMaze() {<br />
$aMaze = new Maze();<br />
$room1 = new Room(1);<br />
$room2 = new Room(2);<br />
$aDoor = new Door($room1, $room2);</p>
<p>$room1-&gt;setSide(North, new Wall());<br />
$room1-&gt;setSide(East, $aDoor);<br />
$room1-&gt;setSide(South, new Wall());<br />
$room1-&gt;setSide(West, new Wall()); </span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;"> $room2-&gt;setSide(North, new Wall());<br />
$room2-&gt;setSide(East, new Wall());<br />
$room2-&gt;setSide(South, new Wall());<br />
$room2-&gt;setSide(West, $aDoor);</p>
<p>$aMaze-&gt;addRoom($room1);<br />
$aMaze-&gt;addRoom($room2);<br />
}<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">In this example, we define a MapSite class that will act as a base class for anything that could apear in a maze, such as a door, a room, or a wall. We then define the constants North, East, South, and West to be used for tracking the sides or orientation of these MapSite objects. Following the constant definitions are the definitions for the Wall, Room and Door classes. These objects should be obvious in intent. </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The setSide() method of the Room class expects the direction of the side and the object to be placed there &#8211; any object derived of the class MapSite. This would typically be a Wall or a Door, but it could support more objects easily. The constructor of the Door class expects two Room objects &#8211; the door must be aware of the rooms it is connecting. Next we define the Maze class, which is used to represent our actual maze object in code. We use the addRoom() method to attach rooms to the maze. </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Finally, we look at the MazeGame class and its createMaze() method. The createMaze() method creates a maze object, two rooms and a door, then defines what objects occupy the sides of the two rooms and attaches them to our Maze object. At this point, we have successfully created a Maze and put some rooms into it.</span></p>
<p class="MsoNormal"><strong><span style="font-size:8.5pt;font-family:Verdana;color:black;">Design Patterns in PHP &#8211; Factory Method and Abstract Factory &#8211; Drawbacks of the Example</span></strong></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Now that you understand the example case, we need to talk about the drawbacks with the implementation used in this example. The main roadblock with using this implementation is that the MazeGame object is hard coded to create specific classes of objects &#8211; that is, it creates Maze, Wall, Door and Room directly without use of any factory methods. We can improve this design by refactoring our createMaze method to use a MazeFactory object for object instantiation. Here is an example.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class MazeFactory {<br />
function MazeFactory() {}<br />
function createMaze() { return new Maze(); }<br />
function createRoom($roomNumber) { return new Room($roomNumber); }<br />
function createDoor($room1, $room2) { return new Door($room1, $room2); }<br />
function createWall() { return new Wall(); }<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class MazeGame {<br />
function createMaze() {<br />
$factory = new MazeFactory();<br />
$aMaze = $factory-&gt;makeMaze();<br />
$room1 = $factory-&gt;makeRoom(1);<br />
$room2 = $factory-&gt;makeRoom(2);<br />
$aDoor = $factory-&gt;makeDoor($room1, $room2);</p>
<p>$room1-&gt;setSide(North, $factory-&gt;makeWall());<br />
$room1-&gt;setSide(East, $aDoor);<br />
$room1-&gt;setSide(South, $factory-&gt;makeWall());<br />
$room1-&gt;setSide(West, $factory-&gt;makeWall()); </span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;"> $room2-&gt;setSide(North, $factory-&gt;makeWall());<br />
$room2-&gt;setSide(East, $factory-&gt;makeWall());<br />
$room2-&gt;setSide(South, $factory-&gt;makeWall());<br />
$room2-&gt;setSide(West, $aDoor);</p>
<p>$aMaze-&gt;addRoom($room1);<br />
$aMaze-&gt;addRoom($room2);<br />
}<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">This method is significantly better because it moves creational knowledge out of the createMaze() method and into the MazeFactory class. This will work fine if we only want to use one family of Maze objects, but what if we want to create subclasses of Wall, Door and Room to allow different behaviors? The examples given in Design Patterns use enchanted rooms and rooms with bombs as examples. </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">An enchanted room could have special behaviors, such as requiring conditions to be met before a door could be opened or closed. A room with a bomb would know what conditions caused a bomb to detonate and would track whether or not the bomb had gone off. If the bomb had gone off, it would keep up with damage to walls from the bomb. If we wanted to use these classes, we would have to parameterize our factory object to check some sort of input condition to know which family of objects to create.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">This is where the Abstract Factory pattern comes in. This pattern uses the Factory Method pattern to handle actual object instantiation, but the value of the Abstract Factory pattern comes at a higher level. We code our calling code not only to use factory methods for object creation but to expect a factory object that conforms to a certain interface. This means that we can use different factories &#8211; all based on a single abstract factory interface &#8211; to create different families of objects. Calling code would only need to expect a class that derives from the original MazeFactory class.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">For brevity&#8217;s sake we will not type out the code to define the subclasses of Room, Wall, and Door, but we will define the subclasses of the MazeFactory object that are used to create enchanted mazes and mazes with bombs in them.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class EnchantedMazeFactory extends MazeFactory {<br />
function makeRoom($roomNumber) { return new EnchantedRoom($roomNumber); }<br />
function makeDoor($room1, $room2) { return new EnchantedDoor($room1, $room2); }<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class BombedMazeFactory extends MazeFactory {<br />
function makeRoom($roomNumber) { return new RoomWithABomb($roomNumber); }<br />
function makeWall() { return new BombedWall(); }<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">We can now use different concrete factory classes to create different families of products &#8211; in this case, different types of Doors, Walls, and Rooms. We are now left with one last problem &#8211; createMaze(), at last glance, is hard coded to create a MazeFactory object. Since createMaze() only needs to create the objects themselves through a standard factory interface, there is no need for the method to ever actually create the factory. We should pass the factory in as an argument to createMaze() and then let the method do its work.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">class MazeGame {<br />
function createMaze($factory) {<br />
$aMaze = $factory-&gt;makeMaze();<br />
$room1 = $factory-&gt;makeRoom(1);<br />
$room2 = $factory-&gt;makeRoom(2);<br />
$aDoor = $factory-&gt;makeDoor($room1, $room2);</p>
<p>$room1-&gt;setSide(North, $factory-&gt;makeWall());<br />
$room1-&gt;setSide(East, $aDoor);<br />
$room1-&gt;setSide(South, $factory-&gt;makeWall());<br />
$room1-&gt;setSide(West, $factory-&gt;makeWall()); </span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;"> $room2-&gt;setSide(North, $factory-&gt;makeWall());<br />
$room2-&gt;setSide(East, $factory-&gt;makeWall());<br />
$room2-&gt;setSide(South, $factory-&gt;makeWall());<br />
$room2-&gt;setSide(West, $aDoor);</p>
<p>$aMaze-&gt;addRoom($room1);<br />
$aMaze-&gt;addRoom($room2);<br />
}<br />
}</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">Now in our createMaze() method, no assumptions are made about the type of factory we need. Some other code that is responsible for figuring out what type of factory to create would actually instantiate the MazeFactory and pass it to createMaze(), as in the following example.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:&quot;color:black;">$game = new MazeGame();<br />
$game-&gt;createMaze(new EnchantedMazeFactory());</span><span style="font-size:8.5pt;font-family:Verdana;color:black;"></span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">After all is said and done, we have created (with a little help from Design Patterns) a very flexible set of classes for producing mazes. It should be noted that in an actual implementation, createMaze() would be using data of some kind to determine what components are required in the maze and the method calls on the various MapSite objects would not be hard coded as they are in the example.</span></p>
<h1><span style="font-size:8.5pt;font-family:Verdana;">Design Patterns in PHP &#8211; Factory Method and Abstract Factory &#8211; Conclusion</span></h1>
<p><span style="font-size:8.5pt;font-family:Verdana;color:black;">The Factory Method and Abstract Factory patterns allow us to build a great deal of flexibility into our applications by abstracting the process of object instantiation and by helping consolidate creational knowledge in the appropriate classes. The Factory Method pattern teaches us how to use methods for object creation rather than directly instantiating objects through client code. This lets the factory method itself do any work it needs to do in creating the object &#8211; work that could involve contextual considerations or initializing certain resources in the object. The Abstract Factory class teaches us how to create groups of related objects with a common interface, creating client code that expects neither a specific type of object nor a specific type of factory.</span></p>
<p><span style="font-size:8.5pt;font-family:Verdana;color:black;">One of the most important concepts in good object oriented design is &#8220;design to an interface, not an implementation.&#8221; What this means is that you should code your application to expect standard sets of object behaviors but not to expect specific object types. This results in a system of objects that know as little as possible about one another and, so long as the interfaces to these classes do not change, the internals of the classes can vary without adversely affecting other classes in the system.</span></p>
<p><span style="font-size:8.5pt;font-family:Verdana;color:black;">In the final createMaze() example above, we see this in action on two levels. First, we pass any MazeFactory type object to the method, which is used to instantiate various MapSite objects and load them into a Maze. Second we are working with the Maze and MapSite objects without worrying about their specific class, just their interface &#8211; we know a Room needs a room number when we create it and we know we can enter a room. It does not matter to the client code that the room may be an EnchantedRoom or a RoomWithABomb &#8211; all it needs to know is how to create it and how to use it. This is the very definition of programming to an interface. The opposite case is true with the first maze example where createMaze() directly creates specific Room, Door, and Wall objects.</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;">The use of these two patterns is a good starting point for programmers just beginning to learn about patterns and good object oriented design. This is the first in what will be a series of articles on design patterns with PHP examples and is intended for developers who are somewhat new to design patterns. Thanks for reading and please don&#8217;t forget to leave some feedback in the comments section!</span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal"><span style="font-size:8.5pt;font-family:Verdana;color:black;"> </span></p>
<p class="MsoNormal">
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathayi.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathayi.wordpress.com/28/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mathayi.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mathayi.wordpress.com/28/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mathayi.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mathayi.wordpress.com/28/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mathayi.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mathayi.wordpress.com/28/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mathayi.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mathayi.wordpress.com/28/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mathayi.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mathayi.wordpress.com/28/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mathayi.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mathayi.wordpress.com/28/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=28&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathayi.wordpress.com/2009/01/19/design-patterns-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6b6115bcb8fd0e144662eb67264cc416?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathayi</media:title>
		</media:content>

		<media:content url="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image001.gif" medium="image">
			<media:title type="html">The factory class and its related IUser interface and user class</media:title>
		</media:content>

		<media:content url="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image002.gif" medium="image">
			<media:title type="html">The IUser interface and the user class with factory methods</media:title>
		</media:content>

		<media:content url="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image003.gif" medium="image">
			<media:title type="html">The database connection singleton</media:title>
		</media:content>

		<media:content url="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image004.gif" medium="image">
			<media:title type="html">The observable user list and the user list event logger</media:title>
		</media:content>

		<media:content url="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image005.gif" medium="image">
			<media:title type="html">The command chain and its related commands</media:title>
		</media:content>

		<media:content url="/DOCUME~1/abint/LOCALS~1/Temp/msohtml1/03/clip_image006.gif" medium="image">
			<media:title type="html">The user list and the strategies for selecting users</media:title>
		</media:content>
	</item>
		<item>
		<title>ZCE Sample questions</title>
		<link>http://mathayi.wordpress.com/2009/01/18/zce-sample-questions/</link>
		<comments>http://mathayi.wordpress.com/2009/01/18/zce-sample-questions/#comments</comments>
		<pubDate>Sun, 18 Jan 2009 19:06:40 +0000</pubDate>
		<dc:creator>mathayi</dc:creator>
				<category><![CDATA[ZCE]]></category>
		<category><![CDATA[ZCE Sample questions]]></category>

		<guid isPermaLink="false">http://mathayi.wordpress.com/?p=9</guid>
		<description><![CDATA[1. Which of the following functions will sort an array in ascending order by value, while preserving key associations? asort() usort() krsort() ksort() sort() 2. A fingerprint of a string can be determined using which of the following? md5() hash() fingerprint() None of the above 3. Consider the following XML document &#60;?xml version="1.0" encoding="ISO-8859-1" ?&#62; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=9&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>1. Which of the following functions will sort an array in ascending order by value, while preserving key associations?</p>
<p>asort()</p>
<p>usort()</p>
<p>krsort()</p>
<p>ksort()</p>
<p>sort()</p>
<p>2. A fingerprint of a string can be determined using which of the following?</p>
<p>md5()</p>
<p>hash()</p>
<p>fingerprint()</p>
<p>None of the above</p>
<p>3. Consider the following XML document</p>
<pre class="code">&lt;?xml version="1.0" encoding="ISO-8859-1" ?&gt;
&lt;!DOCTYPE html
 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt;
 &lt;head&gt;
  &lt;title&gt;XML Example&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
  &lt;p&gt;
   Moved to &lt;&lt;a href="http://example.org/"&gt;http://www.example.org/&lt;/a&gt;.&gt;
   &lt;br&gt;
  &lt;/p&gt;
 &lt;/body&gt;
&lt;/html&gt;</pre>
<p>What is wrong with this document, and how can it be corrected?</p>
<p>The document is completely valid</p>
<p>All special XML characters must be represented as entities within the content of a node</p>
<p>All tags must be closed</p>
<p>You cannot specify a namespace for the  attribute</p>
<p>The DOCTYPE declaration is malformed</p>
<p>4.</p>
<pre class="code">&lt;?php
$a = array(
  1 =&gt; 'red',
  'green',
  'blue',
  'purple' =&gt; array(
    'house' =&gt; 'dog',
    'food' =&gt; 'meal',
    'here' =&gt; 'gone',
    'hello' =&gt; array(
      5 =&gt; 'goodbye',
      8 =&gt; 'something',
      'correct')));
?&gt;</pre>
<p>Which of the following print statements will output the string &#8220;correct&#8221;?</p>
<p>print $a['purple][4][3];</p>
<p>print $a['purple']['hello'][9];</p>
<p>print $a[2][4][3];</p>
<p>print $a[2][4][9];</p>
<p>print $a[4]['hello'][9];</p>
<p>5. If you would like to store your session in the database, you would do which of the following?</p>
<p>It requires a custom PHP extension to change the session handler</p>
<p>Implement the session_set_save_handler() function</p>
<p>Create functions for each session handling step and use session_set_save_handler() to override PHP&#8217;s internal settings</p>
<p>Configure the session.save_handler INI directive to your session class</p>
<p>6. Consider the following PHP script:</p>
<p>get_socket($host1, $port1),<br />
&#8216;data&#8217; =&gt; str_pad(&#8220;&#8221;, 500000, &#8220;A&#8221;));<br />
$write_map[] = array(&#8216;fr&#8217; =&gt; get_socket($host2, $port2),<br />
&#8216;data&#8217; =&gt; str_pad(&#8220;&#8221;, 500000, &#8220;B&#8221;));<br />
$write_map[] = array(&#8216;fr&#8217; =&gt; get_socket($host3, $port3),<br />
&#8216;data&#8217; =&gt; str_pad(&#8220;&#8221;, 500000, &#8220;C&#8221;));</p>
<p>do {<br />
$write_sockets = array();</p>
<p>foreach($write_map as $data) {<br />
$write_sockets[] = $data['fr'];<br />
}</p>
<p>$num_returned = stream_select($r = null, $write_sockets, $e = null, 30);</p>
<p>if($num_returned) {<br />
foreach($write_sockets as $fr) {<br />
foreach($write_map as $index =&gt; $data) {<br />
if($data['fr'] === $fr) {<br />
$len = fwrite($fr, $data['buf']);</p>
<p>if($len) {<br />
$data['buf'] = substr($data['buf'], $len);</p>
<p>if(empty($data['buf'])) {<br />
fclose($data['fr']);</p>
<p>unset($write_map[$index]);<br />
}<br />
}<br />
}<br />
}<br />
}<br />
}<br />
} while(??????????);<br />
?&gt;</p>
<p>What should go in the ??????? above for this script to function properly?</p>
<p>Answer&#8230;<br />
$num_returned &gt; 0<br />
$len &gt; 0<br />
!empty($data['buf'])<br />
count($write_sockets)<br />
count($write_map)</p>
<p>7. Using flock() to lock a stream is only assured to work under what circumstances?</p>
<p>Answer&#8230;<br />
When running in a Linux environment local filesystem<br />
When accessing the stream of the local filesystem<br />
When running in a Windows environment and accessing a share<br />
When accessing a bi-directional stream<br />
When accessing a read-only stream</p>
<p>8.  Which PCRE regular expression will match the string PhP5-rocks?</p>
<p>Answer&#8230;<br />
/^[hp1-5]*\-.*/i<br />
/[hp1-5]*\-.?/<br />
/[hp][1-5]*\-.*/<br />
/[PhP]{3}[1-5]{2,3}\-.*$/<br />
/[a-z1-5\-]*/</p>
<p>9. The <code>______</code> keyword is used to indicate an incomplete class or method, which must be further extended and/or implemented in order to be used.</p>
<p>Answer&#8230;</p>
<table class="formRadio" border="0">
<tbody>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">final</td>
</tr>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">protected</td>
</tr>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">incomplete</td>
</tr>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">abstract</td>
</tr>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">implements</td>
</tr>
</tbody>
</table>
<p>10.  What is the output of?</p>
<pre class="code">function apple($apples = 4)
{
  $apples = $apples / 2;
  return $apples;
}
$apples = 10;
apple($apples);
echo $apples;

Answer...</pre>
<table class="formRadio" border="0">
<tbody>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">2</td>
</tr>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">4</td>
</tr>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">5</td>
</tr>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">10</td>
</tr>
</tbody>
</table>
<p>11 .  Which of the following is the best way to split a string on the &#8220;-=-&#8221; pattern?</p>
<p>Answer&#8230;</p>
<table class="formRadio" border="0">
<tbody>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">They all are equally proper methods</td>
</tr>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">str_split($string, strpos($string, &#8220;-=-&#8221;))</td>
</tr>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">preg_split(&#8220;-=-&#8221;, $string);</td>
</tr>
<tr class="formRadio">
<td class="formRadioText"></td>
<td class="formRadioValue">explode(&#8220;-=-&#8221; $string);</td>
</tr>
</tbody>
</table>
<p>12. Consider the following PHP script fragment:</p>
<p>createElement(&#8216;title&#8217;);</p>
<p>$node = ????????</p>
<p>$title-&gt;appendChild($node);<br />
$head-&gt;appendChild($title);</p>
<p>?&gt;</p>
<p>What should ??????? be replaced with to add a  node with the value of Hello, World!</p>
<p>Answer&#8230;<br />
	$dom-&gt;createTextNode(&#8220;Hello, World&#8221;);<br />
	$dom-&gt;appendElement($title, &#8220;text&#8221;, &#8220;Hello, world!&#8221;);<br />
	$dom-&gt;appendTextNode($title, &#8220;Hello, World!&#8221;);<br />
	$dom-&gt;createElement(&#8216;text&#8217;, &#8220;Hello, World&#8221;);<br />
	None of the above </p>
<p>13. Implementing your own PDO class requires which steps from the list below?</p>
<p>Answers: (choose 3)<br />
	Extending the PDOStatement Class<br />
	Set the PDO::ATTR_STATEMENT_CLASS parameter<br />
	Call the PDO::setStatementClass() method<br />
	Extend the PDO class<br />
	Set the PDO::ATTR_USE_CLASS paramater </p>
<p>14. Which from the following list is not an approrpiate use of an array?</p>
<p>Answers: (choose 1)<br />
	As a list<br />
	All of these uses are valid<br />
	As a Lookup Table<br />
	A Stack<br />
	As a hash table<br />
15. What variable reference would go in the spots indcated by ????? in the code segment below?</p>
<p>Answer&#8230;<br />
	$msg{$i}<br />
	ord($msg);<br />
	chr($msg);<br />
	substr($msg, $i, 2); </p>
<p>16. When is it acceptable to store sensitive information in an HTTP cookie?</p>
<p>Answer&#8230;<br />
	Only under extremely controlled situations<br />
	When the cookie is sent over a secure HTTP request<br />
	When it is encrypted<br />
	It is always acceptable </p>
<p>17. Consider the following PHP string representing an SQL statement:</p>
<p>$query = &#8220;UPDATE users SET password=&#8217;$password&#8217; WHERE username=&#8217;$username&#8217;&#8221;;</p>
<p>Which of the following values for $username or $password would change the behavior of this query when executed?</p>
<p>Answer&#8230;<br />
	None of the above<br />
	$username = &#8220;foobar\&#8217; WHERE username=&#8217;admin&#8217;&#8221;;<br />
	$password = &#8220;foobar&#8217; WHERE username=&#8217;admin&#8217; &#8211;:&#8221;;<br />
	$username = &#8220;foobar\&#8217; WHERE username=&#8217;admin&#8217;&#8221;;<br />
	$password = &#8220;\&#8221;foobar\&#8221; WHERE username=\&#8221;admin\&#8221;"; </p>
<p>18. When attempting to prevent a cross-site scripting attack, which of the following is most important?</p>
<p>Answer&#8230;<br />
	Not writing Javascript on the fly using PHP<br />
	Filtering Output used in form data<br />
	Filtering Output used in database transactions<br />
	Writing careful Javascript<br />
	Filtering all input </p>
<p>19. In a situation where you want one and only one instance of a particular object, the ________ design pattern should be used.</p>
<p>20. Which of the following list of potential data sources should be considered trusted?</p>
<p>Answers: (choose 1)<br />
	None of the above<br />
	$_ENV<br />
	$_GET<br />
	$_COOKIE<br />
	$_SERVER </p>
<p>21.  Which of the following php.ini directives should be disabled to improve the outward security of your application?</p>
<p>Answers: (choose 4)<br />
	safe_mode<br />
	magic_quotes_gpc<br />
	register_globals<br />
	display_errors<br />
	allow_url_fopen </p>
<p>22. The _______ method will be called automatically when an object is represented as a string.</p>
<p>Answer&#8230;<br />
	getString()<br />
	__get()<br />
	__value()<br />
	__toString()<br />
	__getString() </p>
<p>23. Which functions would be needed to translate the following string:</p>
<p>I love PHP 5</p>
<p>to the following?</p>
<p>5 PHP EVOL I</p>
<p>Answers: (choose 2)<br />
	mirror()<br />
	strtoupper()<br />
	toupper()<br />
	str_reverse()<br />
	strrev() </p>
<p>24. When embedding PHP into XML documents, what must you ensure is true in order for things to function properly?</p>
<p>Answer&#8230;<br />
	Disabling of the short_tags PHP.ini directive<br />
	Enabling the asp_tags PHP.ini directive<br />
	That you have XPath support enabled in PHP 5<br />
	That your XML documents are well-formed<br />
	None of the above, PHP can be embedded in XML in all cases. </p>
<p>25. _______ can be used to add additional functionality to a stream, such as implementation of a specific protocol on top of a normal PHP stream implementation.</p>
<p>Answer&#8230;<br />
	Buffered<br />
	Buckets<br />
	Wrappers<br />
	Filters </p>
<p>26. What is the output of the following?</p>
<p>Answer&#8230;<br />
	50<br />
	5<br />
	95<br />
	10<br />
	100 </p>
<p>27.  SQL Injections can be best prevented using which of the following database technologies?</p>
<p>Answers: (choose 1)<br />
	All of the above<br />
	Prepared Statements<br />
	Persistent Connections<br />
	Unbuffered Queries<br />
	Query escaping </p>
<p>28.  What is the output of the following?</p>
<p>Answer&#8230;<br />
	I have 6 apples and 6 oranges<br />
	I have 6 apples and 5 oranges<br />
	I have 5 apples and 6 oranges<br />
	I have 5 apples and 5 oranges </p>
<p>29. What is the best approach for converting this string:</p>
<p>$string = &#8220;a=10&amp;b[]=20&amp;c=30&amp;d=40+50&#8243;;</p>
<p>Into this array?</p>
<p>array(4) {<br />
  ["a"]=&gt;<br />
  string(2) &#8220;10&#8243;<br />
  ["b"]=&gt;<br />
  array(1) {<br />
    [0]=&gt;<br />
    string(2) &#8220;20&#8243;<br />
  }<br />
  ["c"]=&gt;<br />
  string(2) &#8220;30&#8243;<br />
  ["d"]=&gt;<br />
  string(5) &#8220;40 50&#8243;<br />
}</p>
<p>Answer&#8230;<br />
	Write a parser completely by hand, it&#8217;s the only way to make sure it&#8217;s 100% accurate<br />
	Use the parse_str() function to translate it to an array()<br />
	Pass the variable to another PHP script via an HTTP GET request and return the array as a serialized variable<br />
	Just call unserialize() to translate it to an array()<br />
	Write a string parser using strtok() and unserialize() to convert it to an array </p>
<p>30. What is the output of the following code?</p>
<p>Answer&#8230;<br />
	Error; function declarations can not be split over multiple PHP segments.<br />
	Nothing<br />
	1<br />
	2 </p>
<p>31. To destroy one variable within a PHP session you should use which method in PHP 5?</p>
<p>Answer&#8230;<br />
	Unset the variable in $HTTP_SESSION_VARS<br />
	Use the session_destroy() function<br />
	Use the session_unset() function<br />
	unset the variable in $_SESSION using unset()<br />
	Any of the above are acceptable in PHP 5 </p>
<p>32. What is the best measure one can take to prevent a cross-site request forgery?</p>
<p>Answer&#8230;<br />
	Disallow requests from outside hosts<br />
	Add a secret token to all form submissions<br />
	Turn off allow_url_fopen in php.ini<br />
	Filter all output<br />
	Filter all input </p>
<p>33. Given the following PHP script:</p>
<p>&lt;?php </p>
<p>$xmldata = &lt;&lt;&lt; XML</p>
<p>    XML Example</p>
<p>
      <b>Hello, World!</b>
    </p>
<p>XML;</p>
<p>$sxe = simplexml_load_string($xmldata);</p>
<p>$p = $sxe-&gt;body-&gt;p;</p>
<p>$string = ????????</p>
<p>print $string;<br />
?&gt;</p>
<p>What should go in place of ????? above to print the string Hello, World! (with no leading/trailing whitespace or markup)?</p>
<p>Answer&#8230;<br />
	trim(($p[1]));<br />
	trim(strip_tags(($p-&gt;asText())));<br />
	trim(strip_tags(($p-&gt;asXML())));<br />
	trim(($p-&gt;asXML()));<br />
	strip_tags(($p-&gt;asXML())); </p>
<p>34. When working with a database, which of the following can be used to mitigate the possibility of exposing your database credientials to a malicious user?</p>
<p>Answers: (choose 3)<br />
	Moving all database credentials into a single file<br />
	Moving all database credentials outside of the document root<br />
	Restricting access to files not designed to be executed independently<br />
	Setting creditial information as system environment variables<br />
	Using PHP constants instead of variables to store credentials </p>
<p>35. Which of the following are valid PHP variables?</p>
<p>Answers: (choose 4)<br />
	@$foo<br />
	&amp;$variable<br />
	${0&#215;0}<br />
	$variable<br />
	$0&#215;0 </p>
<p>36. Is this code valid only in PHP 4, in PHP 5, or both?</p>
<p>Answer&#8230;<br />
	Both<br />
	PHP 5<br />
	PHP 4 </p>
<p>37. Which of the following aspects of the MVC pattern is used in conjunction with the database?</p>
<p>Answer&#8230;<br />
	Model<br />
	Schema<br />
	Validation<br />
	Controller<br />
	View </p>
<p>38. To ensure that a given object has a particular set of methods, you must provide a method list in the form of an ________ and then attach it as part of your class using the ________ keyword.</p>
<p>Answer&#8230;<br />
	array, interface<br />
	interface, implements<br />
	interface, extends<br />
	instance, implements<br />
	access-list, instance </p>
<p>39.  What is the best way to ensure the distinction between filtered / trusted and unfiltered / untrusted data?</p>
<p>Answer&#8230;<br />
	None of the above<br />
	Never trust any data from the user<br />
	Enable built-in security features such as magic_quotes_gpc and safe_mode<br />
	Always filter all incoming data<br />
	Use PHP 5&#8242;s tainted mode </p>
<p>40. The ______ pattern is extremely useful for creating objects which watch the state of other objects and respond to those changes.</p>
<p>41.  Which two internal PHP interfaces provide functionality which allow you to treat an object like an array?</p>
<p>Answers: (choose 2)<br />
	iteration<br />
	arrayaccess<br />
	objectarray<br />
	iterator<br />
	array<br />
42. What is the output of the following PHP code?</p>
<p> FOO,<br />
               &#8220;FOO&#8221; =&gt; 20);</p>
<p>print $array[$array[FOO]] * $array["FOO"];</p>
<p>?&gt;</p>
<p>Answer&#8230;<br />
	FOO<br />
	100<br />
	200<br />
	20<br />
	10 </p>
<p>43. When an object is serialized, which method will be called, automatically, providing your object with an opportunity to close any resources or otherwise prepare to be serialized?</p>
<p>Answer&#8230;<br />
	__destroy()<br />
	__serialize()<br />
	__destruct()<br />
	__shutdown()<br />
	__sleep() </p>
<p>44. The ____ construct is particularly useful to assign your own variable names to values within an array.</p>
<p>Answer&#8230;<br />
	array_get_variables<br />
	current<br />
	each<br />
	import_variables<br />
	list </p>
<p>45. In an application which will be under high load, SQLite could be useful for what sort of tasks?</p>
<p>Answer&#8230;<br />
	As your primary database<br />
	SQL shouldn&#8217;t be used in a high load environment<br />
	SQLite should only be used for in-memory databases in this environment<br />
	Session Management<br />
	Read-only databases </p>
<p>46. Which of the following is not a valid default stream wrapper for PHP 5, assuming OpenSSL is enabled?</p>
<p>Answer&#8230;<br />
	ftps://<br />
	ftp://<br />
	sftp://<br />
	https://<br />
	http:// </p>
<p>47.  What is the output of the following PHP script?</p>
<p>Answer&#8230;<br />
	643.75<br />
	432<br />
	643<br />
	257<br />
	432.75 </p>
<p>48.  What would you replace ??????? with, below, to make the string Hello, World! be displayed?</p>
<p>Answer&#8230;<br />
	There is no way to do this<br />
	$string = $argv[1];<br />
	$string = $_ARGV[0];<br />
	list($string) = func_get_args();<br />
	$string = get_function_args() </p>
<p>49. SimpleXML objects can be created from what types of data sources?</p>
<p>Answers: (choose 3)<br />
	A String<br />
	An array<br />
	A DomDocument object<br />
	A URI<br />
	A Database resource </p>
<p>50. What is the output of the following code?</p>
<p>function pears(Array $pears)<br />
{<br />
	if (count($pears) &gt; 0)<br />
	{<br />
		echo array_pop($pears);<br />
		pears($pears);<br />
	}<br />
}<br />
$fruit = array(&#8220;Anjo&#8221;, &#8220;Bartlet&#8221;);<br />
pears($fruit);</p>
<p>Answer&#8230;<br />
	Bartlet<br />
	Anjo<br />
	BartletAnjo<br />
	AnjoBartlet<br />
	None / There is an Error </p>
<p>51. What should be replaced in the string ??????? below to open the archive myarchive.gz located in the document root of the www.example.com server and decompress it?</p>
<p>52. Consider the following function:</p>
<p>What conditional should replace the ????? above?</p>
<p>Answer&#8230;<br />
	!in_array(&#8220;Location: $url&#8221;, headers_list())<br />
	!header_exists(&#8220;Location: $url&#8221;)<br />
	!header_location($url)<br />
	$_SERVER['HTTP_LOCATION'] != $url </p>
<p>53. Consider the following code snippet: </p>
<p>Assuming this snippet is a smaller part of a correctly written script, what actions must occur in place of the ????? in the above code snippet to insert a row with the following values: 10, 20.2, foo, string ? </p>
<p>Answer&#8230;<br />
  A transaction must be begun and the variables must be assigned<br />
  Each value must be assigned prior to calling mysqli_bind_param(), and thus nothing should be done<br />
  Use mysqli_bind_value() to assign each of the values<br />
  Assign $myinteger, $mydouble, $myblob, $myvarchar the proper values  </p>
<p>54. When uploading a file using HTTP, which variable can be used to locate the file on PHP&#8217;s local filesystem? </p>
<p>Answer&#8230;<br />
  None of the above<br />
  $_FILES['fieldname']['tmp_name']<br />
  $_FILES['fieldname']<br />
  $_FILES['fieldname'][0]['filename']<br />
  $_FILES['fieldname']['filename']  </p>
<p>55. What is the output of the following code?</p>
<p>something();	  } catch(AnotherException $e) {    $a-&gt;somethingElse();	  } catch(MyException $e) {    print &#8220;Caught Exception&#8221;;  }} catch(Exception $e) {  print &#8220;Didn&#8217;t catch the Exception!&#8221;;}?&gt;</p>
<p>Answer&#8230;<br />
  &#8220;Caught Exception&#8221; followed by &#8220;Didn&#8217;t catch the Exception!&#8221;<br />
  A fatal error for an uncaught exception<br />
  &#8220;Didn&#8217;t catch the Exception!&#8221;<br />
  &#8220;Didn&#8217;t catch the Exception!&#8221; followed by a fatal error<br />
  &#8220;Caught Exception&#8221;  </p>
<p>56. How can you modify the copy of an object during a clone operation?</p>
<p>Answer&#8230;<br />
	Put the logic in the object&#8217;s constructor to alter the values<br />
	Implment your own function to do object copying<br />
	Implement the object&#8217;s __clone() method<br />
	Implement __get() and __set() methods with the correct logic<br />
	Implement the __copy() method with the correct logic </p>
<p>57. If you would like to store your session in the database, you would do which of the following?</p>
<p>Answer&#8230;<br />
	It requires a custom PHP extension to change the session handler<br />
	Implement the session_set_save_handler() function<br />
	Create functions for each session handling step and use session_set_save_handler() to override PHP&#8217;s internal settings<br />
	Configure the session.save_handler INI directive to your session class </p>
<p>58. Which of the following functions were added to PHP 5 for dealing with arrays?</p>
<p>Answers: (choose 2)<br />
	array_intersect_key()<br />
	array_unshift()<br />
	array_diff_key()<br />
	array_merge()<br />
	array_slice() </p>
<p>59. Creating new nodes in XML documents using PHP can be done using which XML/PHP 5 technologies?</p>
<p>Answers: (choose 2)<br />
	XQuery<br />
	XPath<br />
	SimpleXML<br />
	DOM<br />
	SAX </p>
<p>60. In databases that do not support the AUTO_INCREMENT modifier, you must use a _________ instead to auto-generate a numeric incrementing key</p>
<p>61. The following could be better represented as what?</p>
<p>Answer&#8230;<br />
	A switch statement without break statements<br />
	A foreach statement<br />
	A while statement<br />
	A switch statement<br />
	Multiple if statements </p>
<p>62. The following is a common XML structure used in service oriented architectures, what does it represent?</p>
<p> myMethod</p>
<p>   HI!</p>
<p>Answer&#8230;<br />
	None of the above<br />
	A fragment of a complete SOAP request<br />
	XML-RPC<br />
	REST<br />
	SOAP </p>
<p>63. Setting a HTTP cookie on the client which is not URL-encoded is done how in PHP 5?</p>
<p>Answer&#8230;<br />
	Use the setrawcookie() function<br />
	Set the cookies.urlencode INI directive to false<br />
	Use urldecode() on the return value of setcookie()<br />
	Setting the $no_encode parameter of setcookie() to a boolean &#8216;true&#8217;<br />
	All cookies must be URL encoded </p>
<p>64. Consider the following code-snippet, which is taken from a larger application:</p>
<p>This is an example of doing what using the new MySQLi extension?</p>
<p>Answer&#8230;<br />
	Performing a multi-query statement<br />
	Performing a transaction<br />
	Using an unbuffered queries<br />
	Prepared Statements<br />
	Using buffered queries </p>
<p>65. What are the three access modifiers that you can use in PHP objects?</p>
<p>Answers: (choose 3)<br />
	protected<br />
	public<br />
	static<br />
	private<br />
	final </p>
<p>66. What is wrong with the following code?</p>
<p>setValue(10);<br />
$a_copy-&gt;setValue(20);</p>
<p>?&gt;</p>
<p>Answer&#8230;<br />
	You must use return &amp;$newObj instead<br />
	There is nothing wrong with this code<br />
	duplicate() must accept its parameter by reference<br />
	You must use the clone operator to make a copy of an object<br />
	duplicate() must return a reference </p>
<p>67. Which of the following functions will trim leading and/or trailing white space from a string?</p>
<p>Answers: (choose 3)<br />
	ltrim()<br />
	rtrim()<br />
	wtrim()<br />
	trim()<br />
	str_replace() </p>
<p>68. What is wrong with the following code valid in PHP 4 but invalid in PHP 5?</p>
<p>reassign($b);</p>
<p>?&gt;</p>
<p>Answer&#8230;<br />
	Reassigning $this in PHP 5 throws a fatal error<br />
	It is missing access restrictions (public,private,protected) required in PHP 5<br />
	Classes need to implement the OverLoad interface for this behavior in PHP 5<br />
	$b is now an object handle and the reassign() method needs to be declared pass-by-reference </p>
<p>69. Consider the following PHP script:</p>
<p> get_socket($host1, $port1),<br />
                     &#8216;data&#8217; =&gt; str_pad(&#8220;&#8221;, 500000, &#8220;A&#8221;));<br />
$write_map[] = array(&#8216;fr&#8217; =&gt; get_socket($host2, $port2),<br />
                     &#8216;data&#8217; =&gt; str_pad(&#8220;&#8221;, 500000, &#8220;B&#8221;));<br />
$write_map[] = array(&#8216;fr&#8217; =&gt; get_socket($host3, $port3),<br />
                     &#8216;data&#8217; =&gt; str_pad(&#8220;&#8221;, 500000, &#8220;C&#8221;));</p>
<p>do {<br />
  $write_sockets = array();</p>
<p>  foreach($write_map as $data) {<br />
    $write_sockets[] = $data['fr'];<br />
  }</p>
<p>  $num_returned = stream_select($r = null, $write_sockets, $e = null, 30);</p>
<p>  if($num_returned) {<br />
    foreach($write_sockets as $fr) {<br />
      foreach($write_map as $index =&gt; $data) {<br />
        if($data['fr'] === $fr) {<br />
          $len = fwrite($fr, $data['buf']);</p>
<p>          if($len) {<br />
            $data['buf'] = substr($data['buf'], $len);</p>
<p>            if(empty($data['buf'])) {<br />
              fclose($data['fr']);</p>
<p>              unset($write_map[$index]);<br />
            }<br />
          }<br />
        }<br />
      }<br />
    }<br />
  }<br />
} while(??????????);<br />
?&gt;</p>
<p>What should go in the ??????? above for this script to function properly?</p>
<p>Answer&#8230;<br />
	$num_returned &gt; 0<br />
	$len &gt; 0<br />
	!empty($data['buf'])<br />
	count($write_sockets)<br />
	count($write_map) </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathayi.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathayi.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mathayi.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mathayi.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mathayi.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mathayi.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mathayi.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mathayi.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mathayi.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mathayi.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mathayi.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mathayi.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mathayi.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mathayi.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=9&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathayi.wordpress.com/2009/01/18/zce-sample-questions/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6b6115bcb8fd0e144662eb67264cc416?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathayi</media:title>
		</media:content>
	</item>
		<item>
		<title>WordPress is awesome</title>
		<link>http://mathayi.wordpress.com/2009/01/14/wordpress-is-awesome/</link>
		<comments>http://mathayi.wordpress.com/2009/01/14/wordpress-is-awesome/#comments</comments>
		<pubDate>Wed, 14 Jan 2009 12:41:36 +0000</pubDate>
		<dc:creator>mathayi</dc:creator>
				<category><![CDATA[Misc]]></category>

		<guid isPermaLink="false">http://mathayi.wordpress.com/2009/01/14/wordpress-is-awesome/</guid>
		<description><![CDATA[Hi all , Just created an account with wordpress , and i am very much impressed with the effort put forward by the wordpress team . Good job guys , keep it up !<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=3&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hi all ,<br />
Just created an account with wordpress , and i am very much impressed with the effort put forward by the wordpress team . Good job guys , keep it up !</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathayi.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathayi.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mathayi.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mathayi.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mathayi.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mathayi.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mathayi.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mathayi.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mathayi.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mathayi.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mathayi.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mathayi.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mathayi.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mathayi.wordpress.com/3/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathayi.wordpress.com&amp;blog=6169771&amp;post=3&amp;subd=mathayi&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathayi.wordpress.com/2009/01/14/wordpress-is-awesome/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6b6115bcb8fd0e144662eb67264cc416?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathayi</media:title>
		</media:content>
	</item>
	</channel>
</rss>
