Share your knowledge and create a knowledgebase.
PHP’s next edition, V6, includes new features and syntax improvements that will make it easier to use from an object-oriented standpoint. Other important features, such as Unicode support in many of the core functions, mean that PHP V6 is positioned for better international support and robustness.
PHP is already popular, used in millions of domains (according to Netcraft), supported by most ISPs and used by household-name Web companies like Yahoo! The upcoming versions of PHP aim to add to this success by introducing new features that make PHP more usable in some cases and more secure in others. Are you ready for PHP V6? If you were upgrading tomorrow, would your scripts execute just fine or would you have work to do? This article focuses on the changes for PHP V6 — some of them back-ported to versions PHP V5.x — that could require some tweaks to your current scripts.
If you’re not using PHP yet and have been thinking about it, take a look at its latest features. These features, from Unicode to core support for XML, make it even easier for you to write feature-filled PHP applications.
PHP V6 is currently available as a developer snapshot, so you can download and try out many of the features and changes listed in this article. For features that have been implemented in the current snapshot.
Much improved for PHP V6 is support for Unicode strings in many of the core functions. This new feature has a big impact because it will allow PHP to support a broader set of characters for international support. So, if you’re a developer or architect using a different language, such as the Java™ programming language, because it has better internationalization (i18n) support than PHP, it’ll be time to take another look at PHP when the support improves.
Because you can download and use a developer’s version of PHP V6 today, you will see some functions already supporting Unicode strings. For a list of functions that have been tested and verified to handle Unicode.
|
Namespaces are a way of avoiding name collisions between functions and classes without using prefixes in naming conventions that make the names of your methods and classes unreadable. So by using namespaces, you can have class names that someone else might use, but now you don’t have to worry about running into any problems. Listing 1 provides an example of a namespace in PHP.
You won’t have to update or change anything in your code because any PHP code you write that doesn’t include namespaces will run just fine. Because the namespaces feature appears to be back-ported to V5.3 of PHP, when it becomes available, you can start to introduce namespaces into your own PHP applications.
Listing 1. Example of a namespace
<?php namespace XMLNameSpace; class XMLWriter { // Implementation here... } $writer = new XMLNameSpace::XMLWriter(); ?> |
Depending on how you use PHP and what your scripts look like now, the language and syntax differences in PHP V6 may or may not affect you as much as the next features, which are those that directly allow you to introduce Web 2.0 features into your PHP application.
SOAP is one of the protocols that Web services “speak” and is supported in quite a few other languages, such as the Java programming language and Microsoft® .NET. Although there are other ways to consume and expose Web services, such as Representational State Transfer (REST), SOAP remains a common way of allowing different platforms to have interoperability. In addition to SOAP modules in the PHP Extension and Application Repository (PEAR) library, a SOAP extension to PHP was introduced in V5. This extension wasn’t enabled by default, so you have to enable the extension or hope your ISP did. In addition, PEAR packages are available that allow you to build SOAP clients and servers, such as the SOAP package.
Unless you change the default, the SOAP extension will be enabled for you in V6. These extensions provide an easy way to implement SOAP clients and SOAP servers, allowing you to build PHP applications that consume and provide Web services.
If SOAP extensions are on by default, that means you won’t have to configure them in PHP. If you develop PHP applications and publish them to an ISP, you may need to check with your ISP to verify that SOAP extensions will be enabled for you when they upgrade.
As of PHP V5.1, XMLReader and XMLWriter have been part of the core of PHP, which makes it easier for you to work with XML in your PHP applications. Like the SOAP extensions, this can be good news if you use SOAP or XML because PHP V6 will be a better fit for you than V4 out of the box.
The XMLWriter and XMLReader are stream-based object-oriented classes that allow you to read and write XML without having to worry about the XML details.
In addition to having new features, PHP V6 will not have some other functions and features that have been in previous versions. Most of these things, such as register_globals and safe_mode, are widely considered “broken” in current PHP, as they may expose security risks. In an effort to clean up PHP, the functions and features listed in the next section will be removed, or deprecated, from PHP. Opponents of this removal will most likely cite issues with existing scripts breaking after ISPs or enterprises upgrade to PHP V6, but proponents of this cleanup effort will be happy that the PHP team is sewing up some holes and providing a cleaner, safer implementation.
Features that will be removed from the PHP version include:
Citing portability, performance, and inconvenience, the PHP documentation discourages the use of magic_quotes. It’s so discouraged that it’s being removed from PHP V6 altogether, so before upgrading to PHP V6, make sure that all your code avoids using magic_quotes. If you’re using magic_quotes to escape strings for database calls, use your database implementation’s parameterized queries, if they’re supported. If not, use your database implementation’s escape function, such as mysql_escape_string for MySQL or pg_escape_string for PostgreSQL. Listing 2 shows an example of magic_quotes use.
Listing 2. Using magic_quotes (discouraged)
<?php // Assuming magic_quotes is on... $sql = "INSERT INTO USERS (USERNAME) VALUES $_GET['username']"; ?> |
After preparing your PHP code for the new versions of PHP, your code should look like that in Listing 3.
Listing 3. Using parameterized queries (recommended)
<?php // Using the proper parameterized query method for MySQL, as an example $statement = $dbh->prepare("INSERT INTO USERS (USERNAME) VALUES ?"); $statement->execute(array($_GET['username'])); ?> |
Now that support for magic_quotes will be completely removed, the get_magic_quotes_gpc() function will no longer be available. This may affect some of the older PHP scripts, so before updating, make sure you fix any locations in which this functions exists.
The register_globals configuration key was already defaulted to off in PHP V4.2, which was controversial at the time. When register_globals is turned on, it was easy to use variables that could be injected with values from HTML forms. These variables don’t really require initialization in your scripts, so it’s easy to write scripts with gaping security holes. The register_globals documentation provides much more information about register_globals. See Listing 4 for an example of using register_globals.
Listing 4. Using register_globals (discouraged)
<?php // A security hole, because if register_globals is on, the value for user_authorized // can be set by a user sending them on the query string // (i.e., http://www.example.com/myscript.php?user_authorized=true) if ($user_authorized) { // Show them everyone's sensitive data... } ?> |
If your PHP code uses global variables, you should update it. If you don’t update your code to get prepared for newer versions of PHP, consider updating it for security reasons. When you’re finished, your code should look like Listing 5.
Listing 5. Being specific instead (recommended)
<?php function is_authorized() { if (isset($_SESSION['user'])) { return true; } else { return false; } } $user_authorized = is_authorized(); ?> |
The register_long_arrays setting, when turned on, registers the $HTTP_*_VARS predefined variables. If you’re using the longer variables, update now to use the shorter variables. This setting was introduced in PHP V5 — presumably for backward-compatibility — and the PHP folks recommend turning it off for performance reasons. Listing 6 shows an example of register_long-arrays use.
Listing 6. Using deprecated registered arrays (discouraged)
<?php // Echo's the name of the user value given on the query string, like // http://www.example.com/myscript.php?username=ngood echo "Welcome, $HTTP_GET_VARS['username']!"; ?> |
If your PHP code looks like that shown in Listing 6, update it to look like that in Listing 7. Shut off the register_long_arrays setting if it’s on and test your scripts again.
Listing 7. Using $_GET (recommended)
<?php // Using the supported $_GET array instead. echo "Welcome, $_GET['username']!"; ?> |
The safe_mode configuration key, when turned on, ensures that the owner of a file being operated on matches the owner of the script that is executing. It was originally a way to attempt to handle security when operating in a shared server environment, like many ISPs would have. (For a link to a list of the functions affected by this safe_mode change Your PHP code will be unaffected by this change, but it’s good to be aware of it in case you’re setting up PHP in the future or counting on safe_mode in your scripts.
Microsoft Active Server Pages (ASP)-style tags — the shorter version of the PHP tags — are no longer supported. To make sure this is not an issue for your scripts, verify that you aren’t using the <% or %> tags in your PHP files. Replace them with and ?>.
The PHP team is removing support for both FreeType 1 and GD 1, citing the age and lack of ongoing developments of both libraries as the reason. Newer versions of both of these libraries are available that provide better functionality. For more information about FreeType and GD.
The ereg extension, which supports Portable Operating System Interface (POSIX) regular expressions, is being removed from core PHP support. If you are using any of the POSIX regex functions, this change will affect you unless you include the ereg functionality. If you’re using POSIX regex today, consider taking the time to update your regex functions to use the Perl-Compatible Regular Expression (PCRE) functions because they give you more features and perform better. Table 1 provides a list of the POSIX regex functions that will not be available after ereg is removed. Their PCRE replacements are also shown.
Table 1. ereg() functions and their PCRE equivalents
| ereg() function | Similar preg() function |
|---|---|
ereg(), eregi() |
preg_match() |
ereg_replace(), ereg_replacei() |
preg_replace() |
Some of the features mentioned here have also been ported to PHP V5.3, which is scheduled to be released during the first quarter of 2008. You may want to upgrade to V5.3 and start using these features now, so that when you move to V6 of PHP, it’ll be less of a jump. The following list of features have been back-ported to V5.3:
PHP V6 will offer many improvements and will clean up some of the functionality that has been in older versions of PHP. To take advantage of the new features and cleanup, read through the NEWS list, as it will contain the most up-to-date information about what is included (or not included) in PHP V6. You can download developer versions of PHP V6 today and start making sure that your applications are unaffected by the changes. You can also take this opportunity to clean up your own scripts, removing any of the deprecated functions mentioned in this article or updating your syntax to make sure that your applications are supported. Taken from IBM developerworks
Please post your experiences with these design patterns. If you like this post kindly subscribe to our RSS for free updates and articles delivered to you.
Chat applications are very common in social networking sites, dating sites and other web applications where you need your users to interact with each other or even to site admin. Previously, there were many PHP chat applications which needed page refreshing annoying the users. Then came AJAX chat applications which doesn’t need page refresh and looks very similiar like any flash chat applications. Following is a list of PHP AJAX chat applications you can use in your web applicaitons for free.








All the above chat applications are for free but please read their terms and conditions before use in commercial applications.
Shout me your experiences with the above applications their pros and cons. If you like this post kindly subscribe to our RSS for free updates and articles.
Delphi for PHP is a visual IDE for developing applications in PHP. It is based on the same codebase as Delphi, and it implements a library of objects in PHP based on Delphi’s Visual Component Library (VCL). This will make working in Delphi for PHP a familiar experience to current or past Delphi or C++ Builder users. It also means that PHP developers have access to a full suite of pre-made, object-oriented controls for use in their applications.
Here’s a brief tour of Delphi for PHP, which I hope will help you bootstrap yourself into the environment. Because many regular readers are already familiar with Visual Studio, and because I am extremely familiar with it, I will be making many comparisons between Delphi for PHP and Visual Studio. Also, I won’t spend time discussing the PHP language itself, but I will show how the work in the IDE affects the PHP code underneath.
When you start Delphi for PHP, you’ll see a welcome screen that is similar to what you would see in Visual Studio (Figure A). There is a main window for code (which is initially occupied with links to open previous projects and files, news pieces, and so on), surrounded by toolboxes, project management windows, property viewers, and a code structure window, with a tabbed status/debugging window at the bottom.
Figure A
When you start a new project, you will be asked what kind of project to start. For this example, I chose a new Application. This allows us to work with a completely blank slate project (Figure B). As you can see, the main work area is divided between a grid layout of the page and a source code view of the page. The toolboxes now contain information as well.
Figure B
Let’s take a closer look at the Object Inspector (which is used to edit the properties, events, and JavaScript of objects), where much of the action takes place (Figure C).
Figure C

Again, this will look familiar to users of other IDEs. In this case, I will change the value of the Caption property from Unit1 to Test Page. As soon as I do, the <title> tag in the generated code is now changed to Test Page (Figure D) The reason for this is, the caption property was part of the page itself, so it maps to the <title> tag of the page.
Figure D
It’s interesting that the code displayed is generated directly from the object’s properties and cannot be modified. While this may frustrate many users, the reasoning behind it is to eliminate odd discrepancies between the user’s handmade changes and changes made in the IDE.
As expected, you can drag and drop controls from the toolbox (called the Tool Palette) onto our page. In this example, I will place a text box and a button on the page. I can select the controls on the page with the mouse and use the Object Inspector to modify the associated properties, events, and JavaScript. The difference between Events and JavaScript is that Events handles things that occur server-side and JavaScript items are run on the client side. The OnClick event of a button, for example, is run on the server when a postback occurs as a result of clicking the button. So an object with JavaScript for OnClick and an event handler for OnClick would run the JavaScript, perform the page postback, and then run the event handler code on the server. Double clicking an object in the designer will take you to that object’s default event handler and create an empty event handler if you have not already made one.
The final piece of the puzzle is to make the page look good. To do that, I will attach a stylesheet by first creating a style sheet and adding it to the project. From the File menu, choose New, choose Other in the resulting dialog box, select CSS in the tree on the left, and then click OK. If you have an existing stylesheet that you would like to add to the project, you can do so through the Project menu.
Once you add the stylesheet to the project, it is easy (but not obvious) to add it to the page. In the Tool Palette, you scroll down to the System group, select the StyleSheet control, and drop it onto the page. After the stylesheet is added to the page, you can select it and change the FileName property of the control in the Object Inspector to the name of your stylesheet. Once it is added, you will see that the Style property of the controls on your page has a drop-down list populated with the styles in the stylesheet. You will note that the Style property will not include any styles that do not apply to that type of control.
Delphi for PHP formalizes the potential “division of labor” between the presentation and the business logic. In PHP, it is possible to put all of the processing code embedded into the HTML code. But a good number of PHP developers choose to separate their code, putting all of the logic in a separate file and then including it in the file that is officially the page. In Delphi for PHP, there is a complete and formal separation between the code used for the presentation, and the code used for the logic.
A feature that I overlooked while writing this, is that it is possible for the developer to create their own templates for the system, which in turn gives them control over the HTML. This features was not intuitively obvious when using the product and the documentation did not mention it in this context. If you require control over the HTML, you can have it, but it will require some additional effort on your part.
The relative lack of kludge that pervades systems such as ASP.NET and J2EE leads to Delphi for PHP being much less complex in operation and development, which is then reflected in the IDE itself. However, Delphi for PHP may seem too simplistic for many experienced ASP.NET and J2EE developers. I think that many current PHP developers may feel constrained by it, since they have come to expect the full control over HTML that other tools provide them. ASP.NET developers are used to giving up this control to various widgets. The best thing to do is to give the Delphi for PHP free trial a spin, and see if the product is for you.
Courtesy: Techrepublic : Justin James
Shout me your experiences with Codegear’s Delphi for PHP. If you like this post kindly subscribe to our RSS for free updates and articles delivered to you.
Developers are often find Session and cookies to be same but there is one major difference. Sessions are stored on server while cookies are stored on clients machine. Cookies can easily be tampered by an expert hacker where as session is somewhat safe. Still, cookies are used in many web applications. You must have seen “Remember me on this computer” check box.
What is a cookie?
Sometimes it becomes necessary to track certain user details like (No. Of Visits, names, last visit, etc). The client machine stores such information and sends it to the web server whenever there is a request. Cookies data are sent along with the HTTP headers. You can look at this URL to know more about how they work. http:\\www.cookiecentral.com\faq\
Difference between session and cookie?
The key difference would be cookies are stored in your hard disk whereas a session aren’t stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.
Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.
Note: When you issue a session_start() it generates a session ID and places that on the client side in a cookie. There are also some ways to avoid this using the tag rewrite.
How secure is storing password using cookies?
Generally we store the cookies with the username followed by the password. Now we can use any algorithm to encrypt the password before we store then to make it secured. Now we will have the user name and encrypted password stored in the cookie, which again can be played around. A good practice would be to avoid the storing of user name and using a unique ID generated. This is a overhead which we have to compromise to make thinks more secure.
PHP Cookie Function
As told earlier cookie is sent along with the HTTP headers and to do this we have the set_cookie() function.
boolean setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]] )
All the arguments except the name argument are optional. If only the name argument is present, the cookie by that name will be deleted from the remote client. You may also replace any argument with an empty string (”") in order to skip that argument. The expire and secure arguments are integers and cannot be skipped with an empty string. Use a zero (0) instead. The expire argument is a regular Unix time integer as returned by the time() or mktime() functions. The secure indicates that the cookie should only be transmitted over a secure HTTPS connection.
Common Errors
Warning: Cannot modify header information - headers already sent by….
Always ensure there are no white spaces or HTML tags before the cookie function. When you start with a blank line in your PHP file there is a possibility of getting this error.
Quick Code.
This example will allow you to save user name and password on the client PC as cookie and retrieve them when needed.
There are totally three “.php” files used and let me give a short introduction about what they do.
Index.php
This page initially checks whether the cookie has been created or not. If the cookie is created it displays the name and password stored in it.
Login.php
This page is showed when the cookie isn’t created. The user has to select the checkbox if he needs his details to be remembered.
Logout.php
This page deletes the cookie that has been created.
Now I haven’t concentrated much on the design aspect and this tutorial is to demonstrate how cookies are implemented. You may have to redo the entire code to implement it with your site. I hope this doesn’t bother you much.
index.php Code
<?php //Check if cookie is set if (!isset($_COOKIE['cookie_info'])) { echo $_COOKIE['cookie_info']; ?> <body> <form method="POST" action="login.php"> <center><h1>Cookies </h1> <Center> <table border="0" width="auto"> <tr> <td width="33%">Login Name</td> <td width="33%"><input type="text" name="name" size="20"></td> <td width="34%"> </td> </tr> <tr> <td width="33%">Password</td> <td width="33%"><input type="password" name="pass" size="20"></td> <td width="34%"><input type="checkbox" name="set" value="ON">Remember Me</td> </tr> </table> <center> <p><input type="submit" value="Submit" name="sub"> <input type="reset" value="Reset" name="res"></p> </center> </body> </form> <?php } else { //Cookie is set and display the data $cookie_info = explode("-", $_COOKIE['cookie_info']); //Extract the Data $name = $cookie_info[0]; $pass = $cookie_info[1]; echo "<center><h3>Welcome back $name and your password is $pass"; echo "<a href='logout.php'>Logout</a>"; exit; } ?> |
$_COOKIE or $HTTP_COOKIE_VARS is a super global variable which is used to retrieve the data. Once the cookie is set I retrieve the data, which is stored in it. I have used “-“ as delimiter for each field i.e (name-password).
login.php Code
<?php if(empty($_POST['name']) || empty($_POST['pass'])) { ?> <b>Fill All Details </b> <?php exit; } else { //Colllect the details and validate $time = time(); $name = $_POST['name']; $pass =md5($_POST['pass']); $check = $_POST['set']; $db = mysql_connect("localhost", "admin","admin") or die(mysql_error()); mysql_select_db("test",$db) or die(mysql_error()); $query = "select * from Login where name='$name' and password='$pass'"; $sql = mysql_query($query) or die(mysql_error()); $count = mysql_num_rows($sql); if ($count == 1) { $cookie_data = $name.'-'.$pass; if($check=='ON') { if(setcookie ("cookie_info",$cookie_data, $time+3600)==TRUE) { echo "Cookie SET".$cookie_data; ?> <a href='logout.php'>Logout</a> <? } } } else { echo "Authentication Failed"; exit; } } ?> |
The above code authenticated the user and also if the user has opted to save the password and name we store them in a cookie. The password is encrypted using md5 and is concatenated with “-“ hyphen as field separator. Now the $cookie_data variable contains the concatenated string. The setcookie function is used to store the data into a cookie. The first argument is the cookie reference name (in this example “cookie_info”). The second argument is the data that is to be stored and the third would determine how long the cookie is valid. .
In the example the cookie lifetime is set to 1 hour. Now you must be wondering how? The time () function returns the current Unix time stamp. For example “1072724721” actually means Mon, 29 Dec 2003 19:05:21 UTC. Now lets add a 3600 to the Unix time stamp 1072724721 + 3600 = 1072728321 this is actually Mon, 29 Dec 2003 20:05:21 UTC. You need to spend bit of your time looking at mktime and time functions to understand this better. A cookie returns TRUE on successful creation. .
logout.php Code
<?php $time = time(); if (isset($_COOKIE['cookie_info'])) { setcookie ("cookie_info", "", $time - 3600); echo "Logged Out"; } echo $time; ?> |
Destroying a cookie is quite simple and you might also find that we again use the same function for this. Now you might see me subtracting 3600 what do I really mean by this? I am actually rewinding the clock and setting a old time to it. When I subtract 3600 it rewind my clock one hour before. So if you had created a cookie at 9 AM I will set it to 8 AM there by meaning the cookie has expired. I hope I didn’t sound complex. .
Conclusion
I guess the cookies scare has gone after reading this tutorial. Cookies are simple and it’s always a matter of time for you to understand. So right now all you need to practice a bit to get used to what you have learned. Post in your comments and suggestions for me to know what I sounded like.
If you like this post kindly subscribe to our RSS for free updates and articles delivered to you.
Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems, and it also improves code readability for coders and architects who are familiar with the patterns.
Design patterns were introduced to the software community in Design Patterns, by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (colloquially known as the “gang of four”). 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 design patterns, means they can design better buildings more quickly. The same applies to software.
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’re writing a messaging system to provide for loose coupling, or you can say you’re writing an observer, which is the name of that pattern.
It’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’t show huge applications, so you need to think about ways to apply the principles of the example — and not necessarily this exact code — in your larger applications. That’s not to say that you shouldn’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.
Now that you have a sense of what design patterns are and why they’re useful, it’s time to jump into ten design patterns for PHP V5.
Many of the design patterns in the original Design Patterns book encourage loose coupling. To understand this concept, it’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 — parts you thought were completely unrelated.
The problem is tight coupling. 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’t want to tie them together so heavily that they become interlocked.
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 User 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.
The factory pattern is a class that has some methods that create objects for you. Instead of using new 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.
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.
Listing 1. Factory1.php
<?php interface IUser { function getName(); } class User implements IUser { public function __construct( $id ) { } public function getName() { return "Jack"; } } class UserFactory { public static function Create( $id ) { return new User( $id ); } } $uo = UserFactory::Create( 1 ); echo( $uo->getName()."\n" ); ?> |
An interface called IUser defines what a user object should do. The implementation of IUser is called User, and a factory class called UserFactory creates IUser objects. This relationship is shown as UML in Figure 1.
Figure 1. The factory class and its related IUser interface and user class

If you run this code on the command line using the php interpreter, you get this result:
% php factory1.php Jack % |
The test code asks the factory for a User object and prints the result of the getName method.
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’t copied and pasted all over the code base.
Listing 2 shows an example of using factory methods.
Listing 2. Factory2.php
<?php interface IUser { function getName(); } class User implements IUser { public static function Load( $id ) { return new User( $id ); } public static function Create( ) { return new User( null ); } public function __construct( $id ) { } public function getName() { return "Jack"; } } $uo = User::Load( 1 ); echo( $uo->getName()."\n" ); ?> |
This code is much simpler. It has only one interface, IUser, and one class called User that implements the interface. The User class has two static methods that create the object. This relationship is shown in UML in Figure 2.
Figure 2. The IUser interface and the user class with factory methods

Running the script on the command line yields the same result as the code in Listing 1, as shown here:
% php factory2.php Jack % |
As stated, sometimes such patterns can seem like overkill in small situations. Nevertheless, it’s still good to learn solid coding forms like these for use in any size of project.
Some application resources are exclusive 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’s an overhead to keep opening and closing connections, particularly during a single page fetch.
The singleton pattern covers this need. An object is a singleton 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.
Listing 3. Singleton.php
<?php require_once("DB.php"); class DatabaseConnection { public static function get() { static $db = null; if ( $db == null ) $db = new DatabaseConnection(); return $db; } private $_handle = null; private function __construct() { $dsn = 'mysql://root:password@localhost/photos'; $this->_handle =& DB::Connect( $dsn, array() ); } public function handle() { return $this->_handle; } } print( "Handle = ".DatabaseConnection::get()->handle()."\n" ); print( "Handle = ".DatabaseConnection::get()->handle()."\n" ); ?> |
This code shows a single class called DatabaseConnection. You can’t create your own DatabaseConnection because the constructor is private. But you can get the one and only one DatabaseConnection object using the static get method. The UML for this code is shown in Figure 3.
Figure 3. The database connection singleton
![]()
The proof in the pudding is that the database handle returned by the handle method is the same between two calls. You can see this by running the code on the command line.
% php singleton.php Handle = Object id #3 Handle = Object id #3 % |
The two handles returned are the same object. If you use the database connection singleton across the application, you reuse the same handle everywhere.
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.
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 observer, to register itself. When the observable object changes, it sends a message to the registered observers. What those observers do with that information isn’t relevant or important to the observable object. The result is a way for objects to talk with each other without necessarily understanding why.
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.
Listing 4. Observer.php
<?php interface IObserver { function onChanged( $sender, $args ); } interface IObservable { function addObserver( $observer ); } class UserList implements IObservable { private $_observers = array(); public function addCustomer( $name ) { foreach( $this->_observers as $obs ) $obs->onChanged( $this, $name ); } public function addObserver( $observer ) { $this->_observers []= $observer; } } class UserListLogger implements IObserver { public function onChanged( $sender, $args ) { echo( "'$args' added to user list\n" ); } } $ul = new UserList(); $ul->addObserver( new UserListLogger() ); $ul->addCustomer( "Jack" ); ?> |
This code defines four elements: two interfaces and two classes. The IObservable interface defines an object that can be observed, and the UserList implements that interface to register itself as observable. The IObserver list defines what it takes to be an observer, and the UserListLogger implements that IObserver interface. This is shown in the UML in Figure 4.
Figure 4. The observable user list and the user list event logger

If you run this on the command line, you see this output:
% php observer.php 'Jack' added to user list % |
The test code creates a UserList and adds the UserListLogger observer to it. Then the code adds a customer, and the UserListLogger is notified of that change.
It’s critical to realize that the UserList doesn’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 UserList 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.
This pattern isn’t limited to objects in memory. It’s the underpinning of the database-driven message queuing systems used in larger applications.
Building on the loose-coupling theme, the chain-of-command 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.
Listing 5. Chain.php
<?php interface ICommand { function onCommand( $name, $args ); } class CommandChain { private $_commands = array(); public function addCommand( $cmd ) { $this->_commands []= $cmd; } public function runCommand( $name, $args ) { foreach( $this->_commands as $cmd ) { if ( $cmd->onCommand( $name, $args ) ) return; } } } class UserCommand implements ICommand { public function onCommand( $name, $args ) { if ( $name != 'addUser' ) return false; echo( "UserCommand handling 'addUser'\n" ); return true; } } class MailCommand implements ICommand { public function onCommand( $name, $args ) { if ( $name != 'mail' ) return false; echo( "MailCommand handling 'mail'\n" ); return true; } } $cc = new CommandChain(); $cc->addCommand( new UserCommand() ); $cc->addCommand( new MailCommand() ); $cc->runCommand( 'addUser', null ); $cc->runCommand( 'mail', null ); ?> |
This code defines a CommandChain class that maintains a list of ICommand objects. Two classes implement the ICommand interface — one that responds to requests for mail and another that responds to adding users. The UML is shows in Figure 5.
Figure 5. The command chain and its related commands

If you run the script, which contains some test code, you see the following output:
% php chain.php UserCommand handling 'addUser' MailCommand handling 'mail' % |
The code first creates a CommandChain 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 UserCommand or MailCommand, the code falls through and nothing happens.
The chain-of-command pattern can be valuable in creating an extensible architecture for processing requests, which can be applied to many problems.
The last design pattern we will cover is the strategy 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 — 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.
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.
Listing 6. Strategy.php
<?php interface IStrategy { function filter( $record ); } class FindAfterStrategy implements IStrategy { private $_name; public function __construct( $name ) { $this->_name = $name; } public function filter( $record ) { return strcmp( $this->_name, $record ) <= 0; } } class RandomStrategy implements IStrategy { public function filter( $record ) { return rand( 0, 1 ) >= 0.5; } } class UserList { private $_list = array(); public function __construct( $names ) { if ( $names != null ) { foreach( $names as $name ) { $this->_list []= $name; } } } public function add( $name ) { $this->_list []= $name; } public function find( $filter ) { $recs = array(); foreach( $this->_list as $user ) { if ( $filter->filter( $user ) ) $recs []= $user; } return $recs; } } $ul = new UserList( array( "Andy", "Jack", "Lori", "Megan" ) ); $f1 = $ul->find( new FindAfterStrategy( "J" ) ); print_r( $f1 ); $f2 = $ul->find( new RandomStrategy() ); print_r( $f2 ); ?> |
The UML for this code is shown in Figure 6.
Figure 6. The user list and the strategies for selecting users

The UserList class is a wrapper around an array of names. It implements a find method that takes one of several strategies for selecting a subset of those names. Those strategies are defined by the IStrategy 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: