Common design Patterns in PHP development

Source: Internet
Author: User
Tags define abstract php database

first, the factory model

Factory mode is the most commonly used instantiation object pattern, and is a pattern that replaces the new operation with a factory method.

The advantage of using Factory mode is that if you want to change the class name that you instantiate, you can simply change the content of the factory method without having to look for the specific instantiation in the code (new) to be modified. Provides a flexible dynamic expansion mechanism for the system structure, reducing coupling.

<?php

Header (' Content-type:text/html;charset=utf-8 ');

/**

* Simple Factory mode (static Factory method mode)

*/

/**

* Interface people Human

*/

Interface People

{

Public function say ();

}

/**

* Class man inherits People's men

*/

Class Man implements people

{

The say method of realizing people concretely

Public function Say ()

{

Echo ' I am a man <br> ';

}

}

/**

* Class women inherits People's female human

*/

Class women implements people

{

The say method of realizing people concretely

Public function Say ()

{

Echo ' I am a woman <br> ';

}

}

/**

* Class Simplefactoty Factory

*/

Class Simplefactoty

{

static method in a simple factory-used to create a man object

static function Createman ()

{

return new Man ();

}

Static methods in a simple factory-for creating women objects

static function Createwomen ()

{

return new Women ();

}

}

/**

* Specific Call

*/

$man = Simplefactoty::createman ();

$man->say ();

$woman = Simplefactoty::createwomen ();

$woman->say ();


Second, the Strategy model

A policy pattern that encapsulates a specific set of behaviors and algorithms into classes to accommodate specific contexts.  

The strategy model refers to a pattern that involves decision control in a program. The strategy mode function is very powerful, because the core idea of the design pattern itself is the multi-shape idea of object-oriented programming.

Three roles for the policy mode:

1. Abstract policy roles

2. Specific policy roles

3. Environment role (reference to abstract policy role)

Implementation steps:

1. Define abstract role classes (common abstractions that define each implementation)

2. Define a specific policy class (a common way to implement the parent class specifically)

3. Define Environment role classes (Privatization declaration abstract role variables, overloaded construction methods, execution of abstract methods)

Outside of the programming world, there are many examples of policy patterns. For example:

If I need to go to work from home in the morning, I can have a few strategies to consider: I can take the subway, take a bus, walk or other way. Each policy can get the same results, but different resources are used.

<?php

Abstract class Baseagent {//Abstraction policy class

Abstract function PrintPage ();

}

Class to invoke when the client is IE (Environment role)

Class Ieagent extends Baseagent {

function PrintPage () {

Return ' IE ';

}

}

Class to invoke when the client is not IE (environment role)

Class Otheragent extends Baseagent {

function PrintPage () {

Return ' not IE ';

}

}

Class Browser {//Specific policy roles

Public function call ($object) {

return $object->printpage ();

}

}

$bro = new Browser ();

Echo $bro->call (New Ieagent ());

?>


Three, single case mode

Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the entire system.

Singleton mode is a common design pattern, in the computer system, the thread pool, cache, log objects, dialog boxes, printers, database operations, graphics card drivers are often designed as a single case.

The singleton pattern is divided into 3 kinds: Lazy Type single case, a hungry man type single case, registration type single case.

    1. $_instance must be declared as a static private variable

    2. Constructors and destructors must be declared private to prevent the external program new class from losing the meaning of the singleton pattern

    3. The getinstance () method must be set to public, and this method must be called to return a reference to the instance

    4. :: operator can access static and static functions only

    5. New objects will consume memory

    6. Usage Scenario: The most common place is the database connection.

    7. Once an object is generated using singleton mode, the object can be used by many other objects.

    8. Private __clone () method prevents cloning of objects

Singleton mode, which allows an object of a class to create only one. constructor private decoration,
Declare a static GetInstance method that creates an instance of the object in the method. If the instance already exists, it is not created. For example, you only need to create a database connection.


Class Single {

private $name;//Declare a private instance variable

Private Function __construct () {///declares the privately constructed method in order to prevent external code from using new to create the object.

}

static public $instance;//Declare a static variable (a unique instance saved in the class)

static public Function getinstance () {//Declares a getinstance () static method to detect whether an instance object

if (!self:: $instance) Self:: $instance = new self ();

Return self:: $instance;

}

Public Function SetName ($n) {$this->name = $n;}

Public Function GetName () {return $this->name;}

}

$oa = Single::getinstance ();

$ob = Single::getinstance ();

$oa->setname (' Hello World ');

$ob->setname (' Good Morning ');

echo $oa->getname ();//good morning

echo $ob->getname ();//good morning


Iv. Registration Mode

Register the mode to resolve global shares and swap objects. An object that has been created, hangs on a globally available array, and is fetched directly from the array when it is needed. Registers an object on the global tree. Anywhere directly to visit.

<?php

Class Register

{

protected static $objects;

function set ($alias, $object)//Register the object on the global tree

{

Self:: $objects [$alias]= $object;//Place the object on the tree

}

static function Get ($name) {

Return self:: $objects [$name];//get an object registered to the tree

}

function _unset ($alias)

{

Unset (self:: $objects [$alias]);//Remove an object registered to the tree.

}

}


Five, adapter mode

Encapsulates a variety of distinct function interfaces into a unified API.

PHP database operation has mysql,mysqli,pdo three kinds, you can use the adapter mode unified into the same, so that different database operations, unified into the same API. A similar scenario also has the cache adapter,
Different cache functions, such as MEMCACHE,REDIS,FILE,APC, can be unified into the same.

First define an interface (there are several methods, and the corresponding parameters). Then, there are several different situations in which you write several classes to implement the interface. Functions that accomplish similar functions are unified into a consistent approach


Interface Idatabase

<?php

namespace Imooc;

Interface Idatabase

{

Function Connect ($host, $user, $passwd, $dbname);

function query ($sql);

function Close ();

}


<?php

namespace Imooc\database;

Use Imooc\idatabase;

Class MySQL implements Idatabase

{

protected $conn;

Function Connect ($host, $user, $passwd, $dbname)

{

$conn = mysql_connect ($host, $user, $passwd);

mysql_select_db ($dbname, $conn);

$this->conn = $conn;

}

function query ($sql)

{

$res = mysql_query ($sql, $this->conn);

return $res;

}

function Close ()

{

Mysql_close ($this->conn);

}

}


<?php

namespace Imooc\database;

Use Imooc\idatabase;

Class Mysqli implements Idatabase

{

protected $conn;

Function Connect ($host, $user, $passwd, $dbname)

{

$conn = Mysqli_connect ($host, $user, $passwd, $dbname);

$this->conn = $conn;

}

function query ($sql)

{

Return Mysqli_query ($this->conn, $sql);

}

function Close ()

{

Mysqli_close ($this->conn);

}

}


Pdo

<?php

namespace Imooc\database;

Use Imooc\idatabase;

Class PDO implements Idatabase

{

protected $conn;

Function Connect ($host, $user, $passwd, $dbname)

{

$conn = new \pdo ("mysql:host= $host;d bname= $dbname", $user, $passwd);

$this->conn = $conn;

}

function query ($sql)

{

return $this->conn->query ($sql);

}


function Close ()

{

unset ($this->conn);

}

}


Vi. Observer Patterns

1: Observer mode (Observer), when an object state changes, all objects that depend on it are notified and updated automatically.

2: Scene: After an event occurs, a series of update operations are performed. The traditional way of programming is to add the processing logic directly after the code of the event. When the logic of updates increases, the code becomes difficult to maintain.
This approach is coupled, intrusive, and adds new logic to the body code that needs to modify the event.

3: The Observer pattern realizes a low-coupling, non-intrusive notification and update mechanism.


Defines an event-triggering abstract class.

eventgenerator.php

<?php

Require_once ' loader.php ';

Abstract class eventgenerator{

Private $observers = Array ();

function Addobserver (Observer $observer) {

$this->observers[]= $observer;

}

function Notify () {

foreach ($this->observers as $observer) {

$observer->update ();

}

}

}


Define an Observer interface

observer.php

<?php

Require_once ' loader.php ';

Interface observer{

function update ();//This is the logic to be executed after the event has occurred

}

A class that implements the Eventgenerator abstract class for defining an event that occurs


Realize:

Require ' loader.php ';

Class Event extends eventgenerator{

function Triger () {

echo "Event<br>";

}

}

Class Observer1 implements observer{

function Update () {

echo "Logic 1<br>";

}

}

Class Observer2 implements observer{

function Update () {

echo "Logic 2<br>";

}

}

$event = new event ();

$event->addobserver (New Observer1 ());

$event->addobserver (New Observer2 ());

$event->triger ();

$event->notify ();




Common design Patterns in PHP development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.