Archive for 'PHP'
The Chain-of-Command Pattern: OOP Techniques in PHP
Posted on 10. Mar, 2009 by Will Fitch.
The chain-of-command pattern, like most others, assists with maintaining a loose coupling within your classes. By providing a series of classes that implement the ICommand interface and do a specific bit of processing, the developer doesn’t have to care which method to execute.
The ICommand Interface
-
interface ICommand
-
{
-
/**
-
* Run a command
-
* @param string $command_type
-
* @param args $args
-
*/
-
public function onCommandCall($command_type, $args);
-
}
This simple interface provides a method for executing a call to initiate a bit of functionality. Along with the classes that execute the functionality, you’ll need a class to handle the chain. We’ll provide this class with another interface requiring the use of a method to add chains and execute commands:
-
interface ICommandBuilder
-
{
-
/**
-
* Run a command
-
*
-
* @param string $command_type
-
* @param mixed $args
-
*/
-
public function runCommand($command_type, $args);
-
-
/**
-
* Add a new command class
-
*
-
* @param mixed $commanding_class
-
*/
-
public function addCommand($commanding_class);
-
}
The two methods here are used for executing commands and adding new command classes. Let’s build the chain-of-command class.
-
class ChainBuilder implements ICommandBuilder
-
{
-
-
-
public function runCommand($command_type, $args)
-
{
-
{
-
foreach ($this->_commands as $class)
-
{
-
if ($class->onCommandCall($command_type, $args))
-
{
-
return;
-
}
-
}
-
}
-
}
-
-
public function addCommand($commanding_class)
-
{
-
$this->_commands[] = $commanding_class;
-
return $this;
-
}
-
}
The class above provides a mechanism for chaining your requests. You add the necessary commands to execute, then pass requests to runCommand, which will loop through all of the commands until one successfully completes the action, or it exhausts all commands. Here you could add interface checks and throw the necessary exceptions for commands not found, etc.
Let’s add a couple of command implementations: email and stream.
-
class EmailCommand implements ICommand
-
{
-
public function onCommandCall($command, $args)
-
{
-
if ($command == ‘email’)
-
{
-
// send an email with $args
-
return true;
-
}
-
return false;
-
}
-
}
-
-
class StreamCommand implements ICommand
-
{
-
public function onCommandCall($command, $args)
-
{
-
if ($command == ‘writeStream’)
-
{
-
// Write the stream
-
return true;
-
}
-
return false;
-
}
-
}
These commands email a user and write to a stream. Now let’s use them!
Conclusion
At first glance, the chain-of-command pattern may look like overhead. But on a large code base, this code be useful when making a lot of modifications, etc.
Continue Reading
The Observer Pattern: OOP Techniques in PHP
Posted on 09. Mar, 2009 by Will Fitch.
The observer pattern provides another way to maintain loose coupling within your code. It’s an extremely simple pattern and is implemented similarly across languages. There are two parts: the observer and the observable object. Let’s address them both starting with the observer.
The Observer
-
<?php
-
interface IObserver
-
{
-
/**
-
* Method called on event change
-
*
-
* @param mixed $sender
-
* @param mixed $args
-
*/
-
public function onChange($sender, $args);
-
}
-
?>
As you can see from above, the observer implements a single method called onChange. This method is executed when the observable class changes. The first parameter is typically the instance of the class changing and the second arguments relative to the change. Now let’s look at the IObservable interface:
The Observable Object
-
<?php
-
interface IObserverable
-
{
-
/**
-
* Add an observer
-
*
-
* @param mixed $obj
-
*/
-
public function addObserver($obj);
-
}
-
?>
The observable class provides a method for one or more observers to be notified. The observable class needs to maintain a list of these observers and notify them when necessary. A common usage of this is a logging mechanism that needs to be notified when data is created, updated and deleted.
-
<?php
-
-
class UserLogging implements IObserver
-
{
-
-
public function onChange($sender, $args)
-
{
-
// Log the changes (we echo here)
-
}
-
}
-
-
class User implements IObserverable
-
{
-
-
private function notifyObservers($args)
-
{
-
$i < $count; $i++)
-
{
-
$this->_observers[$i]->onChange($this, $args);
-
}
-
}
-
-
public function deleteUser($id)
-
{
-
$db->deleteUser($id);
-
}
-
-
public function addObserver($obj)
-
{
-
// Add logic for interface implementation check here if you want.
-
$this->_observers[] = $obj;
-
}
-
}
-
-
$user = new User();
-
$user->addObserver(new UserLogging());
-
$user->deleteUser(55);
-
?>
Not only does this provide you some pseudo event access, but this is a much cleaner, maintainable implementation of observing a particular object.
Conclusion
I hope you find ways at work to implement this use pattern. We more often than not get caught up with getting code written (it comes with the territory) and lose sight of these power and proven designs to get the job done. I’m certainly just as much to blame as the next developer! Hope this helps!
Continue Reading
The Iterator Pattern: OOP Techniques in PHP
Posted on 04. Mar, 2009 by Will Fitch.
The iterator pattern is one of the most useful, yet unused patterns defined. It provides a way for class users to count and iterate over a set of objects related to the class. This is very useful in MVC (Model-View-Controller) models as they handle data and the logic that pertains to it.
PHP provides two interfaces that already define what you should include in an iterator pattern: Iterator and Countable. Below are their definitions:
Iterator Interface
Countable Interface
-
<?php
-
interface Countable
-
{
-
}
-
?>
You can already iterate over class properties using the foreach() loop, so the Iterator and Countable interfaces are domain specific — meaning the iteration logic is specific to the functionality of the class.
As an example, let’s assume we have a domain model that manages users (CRUD). We have an additional class that acts as a structure (you don’t have to do this, but it’s easier to read in a blog) for each individual user. You also have a method that retrieves an arbitrary number of users, assigns each to a User class (acting as a struct), and gives back an array. While this is certainly doable, the iterator pattern defines an easier way to process the data.
Example Before Iterator Pattern
-
<?php
-
-
class User
-
{
-
public $email;
-
public $address;
-
public $city;
-
public $state;
-
public $zip;
-
}
-
-
class User_Management
-
{
-
/**
-
* List of users
-
*/
-
-
public function getUserByID($id)
-
{
-
// go get a user and assign it an instance of User
-
}
-
-
public function getAllUsers()
-
{
-
// go get all users, assign each to User class, and add to the self::users array
-
}
-
-
}
-
-
?>
The above example is pretty typical for domain models without the use of iterator. Adding the iterator, we provide an interface to bi-directionally traverse, get key information and count records.
With the Iterator Pattern Implemented
-
<?php
-
-
class User
-
{
-
public $email;
-
public $address;
-
public $city;
-
public $state;
-
public $zip;
-
}
-
-
class User_Management implements Iterator, Countable
-
{
-
/**
-
* List of users
-
*/
-
-
/**
-
* Position of the iterator
-
*/
-
private $position=0;
-
-
/**
-
* Retrieve the current record
-
*/
-
{
-
return $this->users[$this->position];
-
}
-
-
/**
-
* Return the current key index
-
*/
-
{
-
return $this->position;
-
}
-
-
/**
-
* Increment the iterator index
-
*/
-
{
-
++$this->position;
-
}
-
-
/**
-
* Reset the position
-
*/
-
{
-
$this->position = 0;
-
}
-
-
public function getUserByID($id)
-
{
-
// go get a user and assign it an instance of User
-
}
-
-
/**
-
* Validate whether a record at current
-
* position exists
-
*/
-
public function valid()
-
{
-
}
-
-
/**
-
* Return the total number of users
-
*/
-
{
-
}
-
-
public function getAllUsers()
-
{
-
// go get all users, assign each to User class, and add to the self::users array
-
}
-
-
}
-
-
?>
The domain model now implements Countable and Iterator. The below example shows a couple of uses for this:
-
<?php
-
-
$iterator = new User_Management();
-
foreach ($iterator as $index => $value)
-
{
-
// The $index will contain the current key
-
// while the $value will contain the user
-
// at the current position
-
}
-
// Rewind the iterator
-
$iterator->rewind();
-
-
while ($iterator->valid())
-
{
-
$value = $iterator->current();
-
$iterator->next();
-
}
-
-
// Rewind the iterator
-
$iterator->rewind();
-
-
for ($iterator->key(); $iterator->valid(); $iterator->next())
-
{
-
$value = $iterator->current();
-
}
-
-
?>
Conclusion
This is a much cleaner, easier approach to iterating over objects. I hope you find this usable in your domain models!
Continue Reading
The Factory Pattern: OOP Techniques in PHP
Posted on 02. Mar, 2009 by Will Fitch.
The purpose of the factory pattern is to assist with maintaining loose coupling. Code that is tightly coupled is error prone in that if a class is changed, it can have a domino affect to other scripts using it. This is typical to large-scale systems and smaller systems that grow very fast.
For example, let’s assume you have a relatively small system that contains a class called Users. This class reads user data from a small file located on disk. Your system booms, and you need to move to a RDBMS (Relational Database Management System). Because of this, your methods in the class, data source and other items change, breaking the code that is utilizing the Users class. This is where the factory pattern comes in.
The factory pattern’s purpose is to contain methods that create objects for you. Instead of directly instantiating the Users class, you request an instance from a factory class (we’ll call it UsersFactory), and call a static method (we’ll call it getInstance).
Example
-
<?php
-
class Users
-
{
-
private $_userId;
-
public function getUserById()
-
{
-
// go get a user
-
}
-
-
public function __construct($id)
-
{
-
$this->_userId = $id;
-
}
-
}
-
-
class UsersFactory
-
{
-
{
-
return new Users($id);
-
}
-
}
-
-
$user = UsersFactory::getInstance($id);
-
?>
The example above demonstrates how a factory method would work. Now, let’s add in that new class that gets the users from the database. Let’s assume you have 25 other scripts that use the existing class. You can create the new Users_From_DB class and create a static method to reference that as well.
-
<?php
-
-
class Users
-
{
-
private $_userId;
-
public function getUserById()
-
{
-
// go get a user
-
}
-
-
public function __construct($id)
-
{
-
$this->_userId = $id;
-
}
-
}
-
-
class Users_From_DB
-
{
-
// same class only from db
-
}
-
-
class UsersFactory
-
{
-
{
-
return new Users($id);
-
}
-
-
{
-
return new Users_From_DB($id);
-
}
-
}
-
?>
This allows you to maintain a loose coupling with a class that could create major problems in the event it goes through major changes.
Conclusion
I have seen where some use the factory pattern as a singleton. They look similar but serve two very different purposes. Take the code below:
-
<?php
-
-
class Users_Model
-
{
-
public function getUserById($id)
-
{
-
// do something
-
}
-
}
-
-
class Model
-
{
-
-
{
-
{
-
return self::$instances[$model_name];
-
}
-
return self::$instances[$model_name] = new $model_name();
-
}
-
}
-
-
$model = Model::factory(‘Users_Model’);
-
$model2 = Model::factory(‘Users_Model’);
-
?>
While the case could be made that it is acting as a factory pattern, it is being used more as a singleton, maintaining a single instance of a class.
The factory pattern does a really good job, and like the singleton, it serves a very specific purpose.
Continue Reading
The Singleton Pattern: OOP Techniques in PHP
Posted on 02. Mar, 2009 by Will Fitch.
The singleton pattern is a common pattern used to make resources exclusive in that there is one of a particular type of resource. The most common usage of this is database connectivity. Typically, an application only wants a single connection to a single database server at any given time. Another use could be restricting the instance to a specific number of objects. This is where the singleton pattern comes in.
The singleton pattern is defined as a design pattern that is used to restrict instantiation of a class to one object (or limit number of instances). This is a pretty straight forward concept and works well with many other OOP techniques including the factory pattern. The easiest implementation is to create a public static method within that class that instantiates a new instance.
Example
-
<?php
-
class DB_Connection
-
{
-
private $_con = null;
-
-
{
-
if ($instance === null)
-
$instance = new DB_Connection();
-
return $instance;
-
}
-
-
public function query($sql)
-
{
-
// DO SOME CODE TO RUN A QUERY HERE
-
}
-
-
public function __destruct()
-
{
-
$this->_con->close();
-
}
-
-
private function __construct()
-
{
-
$this->_con = new DB::connect(‘connection_string’);
-
}
-
-
}
-
?>
You’re probably wondering why the class constructor is private. This seems odd as it’s impossible to create an object from outside the class, right? That’s the point. If we don’t limit the class instantiation, the singleton pattern is useless. The method getInstance() can create an object as it’s a member of that class.
How does the static method work?
The static method getInstance() declares a static variable called instance ($instance). The first time this method is called, the $instance variable’s value is null. We then check if the value is null — if it is, we create a new instance of DB_Connection — if it is not, we return the current instance.
Static variables work by declaring the static keyword, then continuing on with the normal variable initialization. The variable will maintain it’s assigned value (whether changed or not) throughout the life of the script.
The second time the getInstance() is called, the $instance variable contains the instance of DB_Connection, and we will return that value. Regardless of how many instances are created of this class, only one object is initialized.
Conclusion
As you can see, the singleton pattern certainly has it’s uses, albeit specific. Keeping the OOP design patterns in mind makes for a cleaner, easier to maintain code base for future developers picking up your projects.
Continue Reading
Zip Code Web Service Updates
Posted on 12. Jan, 2009 by Will Fitch.
I have updated the zip code web service to fix some issues with the data returned from getLocalTime. Prior to this fix, only the 12 hour format was displayed without the proper meridiem (AM or PM). The time was also off by one hour.
This fix adds two additional children:
- currentMilitaryTime – The 24 hour time format
- currentMeridiemTime – The 12 hour time format with AM or PM
I have left the currentTime element for backwards compatibility. I do plan on removing it when I release the new zip code web service some time this month.
Continue Reading
Call for Zip Code Web Service Methods
Posted on 15. Aug, 2008 by Will Fitch.
I have developed a new version of the zip code web service. This new service offers much more functionality than the previous, including 100% document-literal WS-I/WSDL 1.1 compliancy and SOAP 1.1 and 1.2 capabilities.
Along with this, a Java, PHP, .NET and Ruby SDK will be developed so that you only have to worry about making class calls rather than interfacing with SOAP and the network. I will also be increasing the number of elements returned from 300 to 500.
This new service will require that you register your application (domain only, no login) so that I can get an idea of the usage of this service. Your data will not be shared/sold to anyone, I just want some statistics.
Continue Reading
The Zend Certification Exam: What to Expect
Posted on 27. Apr, 2008 by Will Fitch.
The Zend Certification Exam is a step in the right direction for PHP developers looking to enhance their resume and prove their skills. It is becoming accepted by recruiters worldwide and in some cases, demanded by corporations seeking employees. Achieving this certification is no easy task, though. It requires working experience with PHP, as well as the technologies associated with it.
The test consists of 70 questions and you have 90 minutes to complete them. You may skip between questions and revisit those that you skipped. You will likely finish the examination in 30 to 45 minutes (purely personal experience), so take the other half and check your answers.
Continue Reading
Using PHP Namespaces
Posted on 24. Apr, 2008 by Will Fitch.
PHP 5.3 introduces a much requested feature for object-oriented programmers: namespaces. At the time of this writing, version 5.3 of PHP was in development, but is planned on being released in the near future.
One of the purposes object-oriented programming is to remove ambiguous development and data access items. This basically means identifying common functionality and creating the most reusable framework possible, typically in the form of classes. When creating this functionality, you will begin to have issues with naming conventions and narrowing down functionality even further. To resolve this scoping issue, namespaces allow you to contain those bits of code even more.
Continue Reading
Simple XML (SimpleXML) Tutorial Part 1
Posted on 23. Apr, 2008 by Will Fitch.
With the increasing use of web services and communications via HTTP, XML has become an industry standard for sending and receiving data among systems. Every language seems to have multiple ways to parse XML, each more complicated than the other. This presents a problem for developers.
The majority of the time, developers need to read/write XML files without complex features such as advanced namespacing and XSD validation. It seems that opening an XML file, reading and using the content takes forever as you constantly need to reference hundreds of pages of documentation, Google examples of each method or function in the documentation; it never ends.
Since the release of PHP5, SimpleXML has been available for creating and editing XML files or strings. Don’t let the name fool you, it doesn’t represent the simplicity of its capabilities. It does, however, mean the implementation of this extension is simple! PHP has other XML capabilities such as DOM, XMLWriter and XMLReader in the event you need those advanced features not offered by the native SimpleXML extension.
Continue Reading
SOAP Zip Code Web Service!
Posted on 26. Jul, 2007 by Will Fitch.
I have completed the major functionality to the SOAP integration of the zip code services. The following methods can be used to get the data you need:
- getDistanceByZip – Get the distance from one zip code to another
- getZipsByRadius – Get GPS information within (X) miles of a zip code
- getLocalTime – Get the local time for a zip code
I am going to describe each function in depth, and give examples of each in a few languages. If you have suggestions to this service, feel free to contact me using the contact form.
About the Service
This web service is provided absolutely free. Please don’t abuse this. If requests start getting out of hand and bringing my server to its knees, I will start limiting the number of queries per user per day. I don’t want to do this, but I do like my server actually serving
.
It is an RPC style web service, as it really isn’t complicated and is limited to a very specific audience. It’s also easier for developers to use and understand in comparison to document-literal.


![[del.icio.us]](http://www.willfitch.com/wp-content/plugins/bookmarkify/delicious.png)
![[Digg]](http://www.willfitch.com/wp-content/plugins/bookmarkify/digg.png)
![[Google]](http://www.willfitch.com/wp-content/plugins/bookmarkify/google.png)
![[LinkedIn]](http://www.willfitch.com/wp-content/plugins/bookmarkify/linkedin.png)
![[StumbleUpon]](http://www.willfitch.com/wp-content/plugins/bookmarkify/stumbleupon.png)
![[Windows Live]](http://www.willfitch.com/wp-content/plugins/bookmarkify/windowslive.png)
![[Yahoo!]](http://www.willfitch.com/wp-content/plugins/bookmarkify/yahoo.png)
![[Email]](http://www.willfitch.com/wp-content/plugins/bookmarkify/email.png)