Archive for 'Articles'
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
My Bluetooth Journey
Posted on 25. Jan, 2009 by Will Fitch.
I have recently been exploring Bluetooth technology with Java. The BlueCove project provides an easy to use, platform-independent library for using local and remote Bluetooth devices. If you aren’t pleased with BlueCove, you can use the J2ME version distributed by Sun. So, what can you do with Bluetooth? In short, just about anything.
There aren’t many articles out there over this, so it’s easy to get discouraged as you burn your eyes out attempting to read through loads of namespaces, methods and properties. Documentation is available, but usually only contains namespace members without description. BlueCove provides four examples on their site, and they are VERY useful.
I would love to find some fellow developers out there who would like to team up, research and publish our findings. I plan on doing so regardless, and if you’re interested, contact me at will [at] phpfever.com.
Bluetooth is a hidden gem!
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
“On the Way to the Web: The Secret History of the Internet and Its Founders” Book Review
Posted on 29. Aug, 2008 by Will Fitch.
Michael Banks does an excellent job consolidating the characters involved in the events leading up to the web. My first instinct was to think this book was going to be just another boring “history lesson” of the web. I couldn’t be more wrong.
Michael is very in-depth with the stories associated to each character in his book. While all have their own story, the drama surrounding one character in particular, Bill von Meister, was especially thrilling.
While some aspects of the book will be more appreciated by geeks, it is good for all audiences — geeks, students and your average PC user. I would highly recommend digging into “On the Way to the Web”.
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
What is a Web Service?
Posted on 29. Apr, 2008 by Will Fitch.
A web service is a way for systems to communicate over a network. They can be as simple as an API (e.g. Google Maps) or as complex as a brokered system that handles transactions for multiple requesters and/or providers.
Web services bring with them some huge advantages. Data is packaged via HTTP or HTTPS and can usually bypass firewalls since port 80 and 443 are commonly allowed open. This plays a big role where intranet systems need to communicate but have a very strict set of firewall rules. An example might be an Oracle DB link needing to reach a MySQL server. Typically this is a daunting task as you have to go through the bureaucracy of getting the proper ports opened, get added to one or more access-controlled lists, receive/provide access privileges at the database level, etc. Then there is the issue of direct access to data, either by view, table or procedure; the list goes on and on.
Most of these problems can be eliminated by the use of web services. This article’s objective is to explain, at a high-level, when, why and how web services are used.
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.


![[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)