Code Design Pattern For PHP

Author: | Posted in Code Tricks, PHP, Quick Tips No comments

Code Design Pattern PHP: Code Design patterns not only present useful ways for developing robust software rapidly but also provide a way of encapsulating large data/ideas form outside world in friendly terms. In simple words “Recurring solution for common software development challenges ”.

Common Software Development Challenges:

  1. Building new application while using existing code base.
  2. Building/enhancing application securely, quickly and effectively.
  3. Integrate new/existing application.
  4. Multiple developer programming on the same product.
  5. Varying data source and platform setup.

The Factory Patterns: The factory method is a method/process whose main purpose in life is to create objects. Most commonly (and really per definition) the factory method is an interface method that delegates object instantiation decisions to subclasses. However, it also commonly acceptable to say that a method that creates objects (both of known and unknown classes) is a factory method.

 Example:

<pre><?php
/** * A factory method implementation */
abstract class Creator {
/** * Abstract factory method to be defined by child classes */
abstract public function createObject($type);
}
class ConcreteCreatorA extends Creator {
public function createObject($type) {
switch ($type) {
// Handle cases for concrete classes
}
}
}
class ConcreteCreatorB extends Creator {
public function createObject($type) {
switch ($type) {
// Handle cases for concrete classes
}
}
}
$b = new ConcreteCreatorB;
$b->create('ConcreteProductB');
?></pre>

Advantages: 

  • Encapsulates object creation.
  • Don’t need any information what it is creating.
  • Light weight fast and can be made into a static method.

 

The Singleton Patterns:  The singleton pattern ensures one and only one instance of object exist at a time throughout the application scope.

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.

Example:

<pre><?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" );
?></pre>

Advantages: 

  • Same instance available all times.
  • It can replace global variable declaration.

The Observer Pattern: 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.

Example:

<pre><?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" );
?></pre>

The Strategy Patterns:   In this pattern, algorithms/logic are extracted from complex classes so that they can be replaced easily.It favors composition over inheritance.

Example:

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

Advantages: 

  • Most powerful pattern
  • Flexible
  • Encapsulates what changes need to greater dependability.

 

The Registry Patterns: The Registry Pattern A registry is an object that other objects can use to access data, settings, values and other objects from a sort of internal storehouse.

Example:

<pre><?php
/** * Class that manages registry entries for an application. */
class Registry { /** * Holds the registry labels and values data */
protected static $_register = array();/** * Sets a value into the registry if there is no value with this label already */
public static function set($label, $value) {
if (!isset(self :: $_register [$label])) {
self :: $_register [$label] = $value;
}
}
/** * Gets a value from the registry if there is a label with this value */
public static function get($label) {
if (isset( self :: $_register [$label]) {
return self :: $_register [$label];
}
}
}</pre>

Advantages:

  • Maintain a value throughout the request.
  • set/get config values.
  • Allow access variable throughout request scope with global.

 

The Lazy Load Pattern: The Lazy Load Pattern Lazy loading is the process of delaying the instantiate of an object until the instance is needed. We all know the mantra, lazy programmers are the best programmers.

Example:

<pre><?php
/** * Sample class */
class MyClass { /** * Holder for the SomeObject object * * @access protected * @var SomeObject */
protected $_myobject = null;/** * Get the instance of SomeObject, but only when we need it * * @access public * @return SomeObject */
public function fetchObject() {
if ($this->_myobject === null) {
$this->_myobject = new SomeObject;
} return $this->_myobject;
}
}</pre>

Advantages:

  • Delays resource consumption until it needed.
  • Offers an encapsulated means of creating objects
  • Offers an encapsulated means of storing objects for use later
Tags:,