5 Extremely Resourceful PHP Design Patterns for Designers and Developers

83 Flares Twitter 18 Facebook 28 Google+ 36 StumbleUpon 1 Pin It Share 0 83 Flares ×
Rating:

The time has come for the developers to up their PHP development skills with a notch or two. In this article we shall be discussing 5 fundamental PHP coding design factors which can be accessed by PHP developers from all across the world to achieve a systematic, thorough and less time consuming coding design. And since these design patterns were already developed in a problem solving manner, you need not question their resourcefulness; merely choose the model which enables you to best achieve the functionality or the advantage that you are looking for.

5 Noteworthy PHP Design Patterns

1. The Factory Pattern

The factory design pattern is a rather advanced and much widely used pattern for designing codes in PHP. The reason backing up the strong popularity of this platform is that it allows developers to combat tight coupling. Coupling is a reason why most of the applications fail in the first place, especially the large scale ones. Mostly, different programs of an application often refer to a few basic fundamental classes, and an error in one such entity results in the breakdown of some complete isolated class or function – that is the problem caused by tight coupling.

In a case where a number of codes rely on the given files and classes, and if eventually in the development cycle, you need to change these classes, that is when the factory design pattern comes to your rescue. The Factory Pattern actually somehow creates objects for the developers. Hence instead of using the class directly, developers get to utilize factory class to develop various objects. Thus, if one needs to change the type of object created, one can just change the factory object, without disrupting the previously existing class.

Given below is an example of Factory Class:

<?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” );
?>

There exists an interface, typically known as IUser, which entails information regarding the working of the object. When we implement IUser, it is referred to as User and the factory class is known as UserFactory, which primarily created IUser objects.

When the code was executed in the PHP interpreter, it revealed the following line:

% php factory1.php
Jack
%


The test code demands for a User object and in return displays the result obtained in the getName method.

Now we come to a variation of the same method. If you are required to create an object prior to setting various attributes, we’ll let you know how to do the same, so that complex initialization codes would not be carried forward in the entire code base structures. The method is referred to as Factory Methods.

<?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” );
?>


Compared to the previous code, this is quite simpler; as it contains just a single given interface IUser and a class, User, which is used to implement the interface.

Figure: The IUser Interface along with User Class and Factory Methods

When executed on the command line, it yielded the same result as the previous codes:

% php factory2.php
Jack
%

Lastly, this pattern is best suited for developing large scale applications and isn’t the most appropriate match for the smaller ones.

2. The Chain of Command Pattern

It follows a chain of command, as quite evident from the name itself, with a series of handlers. The message or query is run through a series of these handlers and at each junction it is regulated whether the handler can handle the query or not. The process stops the moment a handler can handle the request. These handlers can be removed from the system, with no consequences on the other handlers.

<?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 );
?>

Here, a CommandChain class is defined, which contains a number of ICommand objects. Two classes respond to this interface – one handling mails and other dealing with users.

When running the script containing a test code, the following output was received:

% php chain.php
UserCommand handling ‘addUser’
MailCommand handling ‘mail’
%

This is an important design pattern, use mostly for developing an extensive architecture that processes various requests and takes care of a wide category of problems.

3. The Adapter Pattern

And adapter pattern proves out to be the best design pattern when you have to convert a data object of one time into the other. Although developers have typically used assignment codes, this pattern provides for a very clean, optimized and systematic way of doing the same.

Example: Using this pattern to assign values amongst different objects.

class AddressDisplay
{
private $addressType;
private $addressText;
public function setAddressType($addressType)
{
$this->addressType = $addressType;
}
public function getAddressType()
{
return $this->addressType;
}
public function setAddressText($addressText)
{
$this->addressText = $addressText;
}
public function getAddressText()
{
return $this->addressText;
}
}
class EmailAddress
{
private $emailAddress;
public function getEmailAddress()
{
return $this->emailAddress;
}
public function setEmailAddress($address)
{
$this->emailAddress = $address;
}
}
$emailAddress = new EmailAddress();
/* Populate the EmailAddress object */
$address = new AddressDisplay();
/* Assignment code can be seen where the values are assigned from one object to another. */
$address->setAddressType(“email”);
$address->setAddressText($emailAddress->getEmailAddress());

In this example we have used the obhect AddressDisplay and displayed to our users an address that has two parts: Address Type and Address String. Now see the working of

Adapter Pattern in action:
Example: The adapter pattern

class EmailAddressDisplayAdapter extends AddressDisplay
{
public function __construct($emailAddr)
{
$this->setAddressType(“email”);
$this->setAddressText($emailAddr->getEmailAddress());
}
}
$email = new EmailAddress();
$email->setEmailAddress(“user@example.com”);
$address = new EmailAddressDisplayAdapter($email);
echo($address->getAddressType() . “\n”) ;
echo($address->getAddressText());

4. The Decorator Pattern

The decorator code is yet another revolution in the field of PHP design patterns, as it allows the developers to include functionality in any of the models with a nice, clean and well systematic class. Each of the class only concentrates on the tasks that it has to perform and how they would be included in the base model.

The chief advantage of this platform is that it allows the developers to use more than one decorator at a single given base time. Mostly, stream constructs make use of decorator platform and if you have worked around stream objects, chances are that you must already be familiar with this platform.

5. The Delegate Pattern

With the help of this pattern, developers can delegate work, based in different criteria. In the example below, there is a code containing different conditions. Depending on these conditions, the code selects the object appropriate to handle the requests:

pkg = new Package(“Heavy Package”);
$pkg->setWeight(100);
if ($pkg->getWeight() > 99)
{
echo( “Shipping ” . $pkg->getDescription() . ” by rail.”);
} else {
echo(“Shipping ” . $pkg->getDescription() . ” by truck”);
}
Now check out how the same task can be easily exercised with the delegate pattern:
require_once(‘classes.php’);
$pkg = new Package(“Heavy Package”);
$pkg->setWeight(100);
$shipper = new ShippingDelegate();
if ($pkg->getWeight() > 99)
{
$shipper->useRail();
}
$shipper->deliver($pkg);

The delegate pattern is superior, is it allows for the dynamic change in the behavior pattern by accessing the useRail() or useTruck().

Leave a Reply

Your email address will not be published. Required fields are marked *

 
GET A QUOTE

Get a Quote from Top Web Agency in the World

  • *
  • *
  • *
  • *
  • NOTE: All (*) fields are mandatory.
  • *captcha

    Enter the characters that are displayed in the image on left. They are case sensitive!