WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
Internet Security Software
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
פרייסז - הכח לקנות עובר לידיים שלך
Texas Holdem Poker Evangelists
Patterns

Patterns

Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.

Factory

The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.

Example #1 Parameterized Factory Method

<?php
class Example
{
    
// The parameterized factory method
    
public static function factory($type)
    {
        if (include_once 
'Drivers/' $type '.php') {
            
$classname 'Driver_' $type;
            return new 
$classname;
        } else {
            throw new 
Exception('Driver not found');
        }
    }
}
?>

Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:

<?php
// Load a MySQL Driver
$mysql Example::factory('MySQL');

// Load an SQLite Driver
$sqlite Example::factory('SQLite');
?>

Singleton

The Singleton ensures that there can be only one instance of a Class and provides a global access point to that instance. Singleton is a "Gang of Four" Creational Pattern.

The Singleton pattern is often implemented in Database Classes, Loggers, Front Controllers or Request and Response objects.

Example #2 Singleton example

<?php
class Example
{
    private static 
$instance;
    private 
$count 0;

    private function 
__construct()
    {
    }

    public static function 
singleton()
    {
        if (!isset(
self::$instance)) {
            echo 
'Creating new instance.';
            
$className __CLASS__;
            
self::$instance = new $className;
        }
        return 
self::$instance;
    }

    public function 
increment()
    {
        return 
$this->count++;
    }

    public function 
__clone()
    {
        
trigger_error('Clone is not allowed.'E_USER_ERROR);
    }

    public function 
__wakeup()
    {
        
trigger_error('Unserializing is not allowed.'E_USER_ERROR);
    }
}
?>

Illustrated below is how the Singleton behaves

<?php
$singleton 
Example::singleton(); // prints "Creating new instance."
echo $singleton->increment(); // 0
echo $singleton->increment(); // 1

$singleton Example::singleton(); // reuses existing instance now
echo $singleton->increment(); // 2
echo $singleton->increment(); // 3

// all of these will raise a Fatal Error
$singleton2 = new Example;
$singleton3 = clone $singleton;
$singleton4 unserialize(serialize($singleton));
?>
Warning

The Singleton pattern is one of the more controversial patterns. Critics argue that Singletons introduce Global State into an application and tightly couple the Singleton and its consuming classes. This leads to hidden dependencies and unexpected side-effects, which in turn leads to code that is harder to test and maintain.

Critics further argue that it is pointless to use a Singleton in a Shared Nothing Architecture like PHP where objects are unique within the Request only anyways. It is easier and cleaner to create collaborator object graphs by using Builders and Factory patterns once at the beginning of the Request.

Singletons also violate several of the "SOLID" OOP design principles and the Law of Demeter. Singletons cannot be serialized. They cannot be subtyped (before PHP 5.3) and won't be Garbage Collected because of the instance being stored as a static attribute of the Singleton.