«

»

Jan 29

Design Patterns in PHP

Design patterns were introduced by gang of four group (Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides). The Concept behind design patterns are simplified software development way. It is not only simplified way of software development it is also the way of developing software faster.

Categories of Design Pattern

1.  Creational

  • Abstract Factory
  • Builder
  • Simple Factory
  • FactoryMethod
  • StaticFactory
  • Prototype
  • Singleton
  • Multiton

2.  Structural

  • Adapter
  • Composite
  • Decorator
  • Facade
  • Proxy
  • Registry
  • FluentInterface
  • DataMapper
  • DependencyInjection

3.  Behavioral

  • ChainOfResponsibilities
  • Command
  • Iterator
  • Mediator
  • NullObject
  • Observer
  • Specification
  • State
  • Strategy
  • TemplateMethod
  • Visitor

Some Important Design pattern describe bellow

1. Singleton

class Singleton
{

protected static $instance;

public static function getInstance()
{

if (null === static::$instance) {
static::$instance = new static;
}

return static::$instance;
}

private function __construct(){}

private function __clone(){}

private function __wakeup(){}
}

1. Simple Factory

interface IUser
{
function getName();
}

class User implements IUser
{
public function __construct( $id ) { }

public function getName()
{
return “Mark”;
}
}

class UserFactory
{
public static function Create( $id )
{
return new User( $id );
}
}

$uo = UserFactory::Create( 1 );
echo( $uo->getName().”\n” );

1. Strategy Pattern

interface IStrategy
{
function filter( $record );
}

class Strategy implements IStrategy
{
private $_name;

public function __construct( $name )
{
$this->_name = $name;
}

public function filter( $record )
{
return strcmp( $this->_name, $record ) <= 0; } } class Randomnumber implements IStrategy { public function filter( $record ) { return rand( 0, 1 ) >= 0.5;
}
}

class UserList
{
private $ulist = array();

public function __construct( $names )
{
if ( $names != null )
{
foreach( $names as $name )
{
$this->ulist []= $name;
}
}
}

public function add( $name )
{
$this->ulist []= $name;
}

public function find( $filter )
{
$recs = array();
foreach( $this->ulist as $user )
{
if ( $filter->filter( $user ) )
$recs []= $user;
}
return $recs;
}
}

$ul = new UserList( array( “Tom”, “Herry”, “Luis”, “Philip” ) );
$f1 = $ul->find( new Strategy( “J” ) );
print_r( $f1 );

$f2 = $ul->find( new Randomnumber() );
print_r( $f2 );

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>