PHP Common Design Patterns

Source: Internet
Author: User

    • Singleton mode (ensures that a class is instantiated only once and can be instantiated by itself)
    • Factory mode (replaces the new operation)
    • Strategy mode (use different methods to achieve the same purpose)
    • Observer mode (When an object changes, other objects also trigger the corresponding action)
    • Adapter mode (encapsulates different methods into a unified approach)
    • Registration mode (putting an instance into an array for invocation)

These design patterns are useful in common PHP frameworks: thinkphp, Yii2, and so on.

 /* * * Singleton mode * Ensure that there is only one instance of this class and can instantiate it by itself * used in: Database operations, log objects, etc. */class single{public $db = NULL;    static $instance = null;        Public Function __construct () {$this->db = new mysqli (' 127.0.0.1 ', ' root ', ' root ', ' test ');        if ($this->db->connect_error) {die (' Connect error: '. $this->db->connect_error);    } echo "MySQL connect successful\n"; } static Public Function getinstance () {if (!) (            Self:: $instance instanceof Self)} {self:: $instance = new self ();        echo "aaa\n";        } echo "bbb\n";    Return self:: $instance;    Public Function __destruct () {$this->db->close (); }}single::getinstance (); single::getinstance ();//output:/* MySQL connect successful AAA BBB bbb*/ 
 /** * Factory mode * Use Factory method instead of a mode of new operation */interface people{public function Say ();}    Class Man implements people{public function say () {echo ' I am man \ n ';    }}class woman implements people{public function say () {echo "I am woman \ n";    }}class factory{Public Function Createman () {Return to New Man ();    } public Function Createwoman () {return new woman (); }} $f = new factory (), $f->createman ()->say (), $f->createwoman ()->say (),//output//I am man I am woman */ 

 /** * Strategy mode [use different ways to achieve the same purpose] * scene: Take different means of transport to the company */abstract Class tools{abstract function working ();} Class Bicyle extends tools{public Function working () {echo __method__.    "\ n"; }}class Car extends tools{public Function working () {echo __method__.    "\ n";    }}class transport{Public Function running ($obj) {$obj->working (); }/** * Use magic Method can also achieve the above effect * @param type $name * @param type $arguments */Public function __call ($name    , $arguments) {$arguments [0]-> $name (); }} $t = new transport (), $t->running (New Car ()), $t->running (New Bicyle ()), $t->working (New Car ());// The above effects can also be achieved using the Magic method//Output//car::working bicyle::working car::working */ 
 /* Observer mode * When an object state changes, all objects that depend on it receive a trigger action * occurrence scene: Yii2 's behavior,event */interface event{function Run ();} Class E1 implements event{Public function run () {echo __method__.    "\ n"; }}class E2 implements event{Public function run () {echo __method__.    "\ n";        }}class observer{static $obs;    function Addobs ($name, $obj) {self:: $obs [$name] = $obj;        } function trigger () {foreach (self:: $obs as $val) {$val->run (); }}} $o = new observer (), $o->addobs (' E1 ', New E1 ()), $o->addobs (' E2 ', New E2 ()), $o->trigger ();//output//E1::run E2: : Run */ 
 /* * Adapter Mode * Encapsulates different methods into a unified method for invocation * used in database MySQL, mysqli, PDO, etc. */interface db{public function connect ();    Public function query (); Public function Close ();}        Class Mysqla implements db{public $db;    Public Function Connect () {$this->db = Mysqli_connect ($host, $user, $password, $database, $port, $socket);    Public Function query () {} public Function close () {mysqli_close ($this->db);        }}class MYSQLB implements db{public $db;    Public Function Connect () {$this->db = new PDO ($DSN, $username, $password);    Public Function query () {} public Function close () {$this->db = null; }}
/*  * 注册模式 * 把已有对象放入一个数组里以供调用 */class register{    static $objects;        public static function set($name, $obj){        self::$objects[$name] = $obj;    }    public static function get($name){        return self::$objects[$name];    }}class log{};register::set(‘log‘, new log());$log = register::get(‘log‘);

PHP Common Design Patterns

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.