Several common design patterns in PHP

Source: Internet
Author: User

1. Factory Model

 

Factory mode is a type that provides methods for creating objects for you. You can use the factory class to create objects without directly usingnew. In this way, if you want to change the type of the created object, you only need to change the factory. All codes used in the factory are automatically changed.

 

<? Php <br/> interface iuser // defines an interface <br/>{< br/> function getname (); <br/>}</P> <p> class user implements iuser // defines a class to inherit this interface, and all methods for implementing this interface <br/>{< br/> public function _ construct ($ id) {}</P> <p> Public Function getname () <br/>{< br/> return "Jack "; <br/>}</P> <p> class userfactory // defines a class that can be called directly by using a public static method, new instantiation is not required <br/>{< br/> Public static function create ($ id) <br/>{< br/> return new user ( $ Id); <br/>}</P> <p> $ uo = userfactory: Create (1 ); <br/> echo ($ uo-> getname (). "/N"); <br/>?> <Br/>

 

Another simpler factory model:

<? Php <br/> interface iuser // defines an interface <br/>{< br/> function getname (); <br/>}</P> <p> class user implements iuser // class of the inherited interface <br/>{< br/> Public static function load ($ id) // load the method of this class statically and return the object <br/>{< br/> return new user ($ id ); <br/>}</P> <p> Public static function create () // same as above, but no parameter is required <br/>{< br/> return new user (null ); <br/>}</P> <p> public function _ construct ($ id) {}</P> <p> Public Function get Name () // method in the implementation interface <br/>{< br/> return "Jack "; <br/>}</P> <p> $ uo = User: load (1 ); <br/> echo ($ uo-> getname (). "/N"); <br/>?> </P> <p>

 

 

Single element mode:

 

Some application resources are exclusive because there is only one resource of this type. For example, the connection from a database handle to a database is exclusive. You want to share the database handle in the application, because it is an overhead when you keep the connection open or closed, especially when you get a single page.

The single-element mode can meet this requirement. If an application contains only one object each time, the object is a singleton ). The code in listing 3 shows a single database connection element in PHP V5.

 

You can use global variables to store database handles. However, this method is only applicable to small applications. In large applications, avoid using global variables and use objects and methods to access resources.

 

<? Php <br/> require_once ("DB. PHP "); // load the database configuration file </P> <p> class databaseconnection // database connection class <br/>{< br/> Public static function get () // static common method () <br/>{< br/> static $ db = NULL; // set static variables to null <br/> if ($ db = NULL) // If the static variable is null, perform the following operations <br/> $ db = new databaseconnection (); <br/> return $ dB; <br/>}</P> <p> private $ _ HANDLE = NULL; // set a private variable </P> <p> private function _ construct () // set a private initialization method <br/>{< br/> $ DSN = 'mysql: // root: password @ localhost/photos'; <br/> $ this-> _ HANDLE = & DB: connect ($ DSN, array (); <br/>}</P> <p> public function handle () <br/>{< br/> return $ this-> _ HANDLE; <br/>}</P> <p> Print ("handle = ". databaseconnection: Get ()-> handle (). "/N"); <br/> Print ("handle = ". databaseconnection: Get ()-> handle (). "/N"); <br/>?>

 

 

The observer mode provides another way to avoid close coupling between components. This mode is very simple: an object becomes observability by adding a method (This method allows another object, that is, the observer registers itself. When an observed object changes, the message is sent to the registered observer. The operations performed by these observers using this information are irrelevant to the observed objects. The result is that objects can communicate with each other without understanding the cause.

A simple example is the user list in the system. The code in Listing 4 shows a user list. When a user is added, it sends a message. When a user is added, the list can be observed by the log observer who sends the message.

 

<? Php <br/> interface iobserver // defines an interface <br/> {<br/> function onchanged ($ sender, $ ARGs ); <br/>}</P> <p> interface iobservable // define an interface <br/>{< br/> function addobserver ($ observer ); <br/>}</P> <p> class userlist implements iobservable // inherit the second interface <br/>{< br/> private $ _ Observers = array (); </P> <p> Public Function addcustomer ($ name) <br/> {<br/> foreach ($ this-> _ observers as $ obs) <br/> $ obs-> onchan Ged ($ this, $ name); // call the observer interface to use multiple interfaces <br/>}</P> <p> Public Function addobserver ($ observer) // Add the observer Mode Interface <br/>{< br/> $ this-> _ observers [] = $ observer; <br/>}</P> <p> class userlistlogger implements iobserver // inherits the first interface <br/>{< br/> Public Function onchanged ($ sender, $ ARGs) <br/>{< br/> echo ("'$ ARGs' added to user list/N "); <br/>}</P> <p> class userlistlogger2 implements iobserver // Inherit the first interface 2 <br/>{< br/> Public Function onchanged ($ sender, $ ARGs) <br/>{< br/> echo ("'$ ARGs' 2222222222222222 list/N "); <br/>}</P> <p> $ ul = new userlist (); <br/> $ ul-> addobserver (New userlistlogger (); <br/> $ ul-> addobserver (New userlistlogger2 ()); <br/> $ ul-> addcustomer ("Jack"); <br/>?>

 

 

Command Chain Mode

The command chain mode sends messages, commands, and requests based on loosely coupled topics, or sends arbitrary content through a set of handlers. Each handler determines whether it can process the request. If yes, the request is processed and the process stops. You can add or remove a handler for the system without affecting other handlers.

 

In general, the command chain mode allows the system to define multiple execution interfaces and execute them through one command link port!

 

<? Php <br/> interface icommand // defines an interface <br/>{< br/> function oncommand ($ name, $ ARGs ); <br/>}</P> <p> class commandchain // a command Link Interface Class <br/>{< br/> private $ _ commands = array (); </P> <p> Public Function addcommand ($ cmd) // added the command link port <br/>{< br/> $ this-> _ commands [] = $ cmd; <br/>}</P> <p> Public Function runcommand ($ name, $ ARGs) // execute the command chain function interface <br/>{< br/> foreach ($ this-> _ commands as $ cmd) <br/>{< br/> If ($ Cmd-> oncommand ($ name, $ ARGs) <br/> return; <br/>}</P> <p> class usercommand implements icommand // defines an interface class <br/>{< br/> Public Function oncommand ($ name, $ ARGs) <br/>{< br/> if ($ name! = 'Adduser') return false; <br/> echo ("usercommand handling 'adduser'/N"); <br/> return true; <br/>}</P> <p> class mailcommand implements icommand // defines an interface class <br/>{< br/> Public Function oncommand ($ name, $ ARGs) <br/>{< br/> if ($ name! = 'Mail') return false; <br/> echo ("mailcommand handling 'mail'/N"); <br/> return true; <br/>}</P> <p> $ cc = new commandchain (); <br/> $ CC-> addcommand (New usercommand (); <br/> $ CC-> addcommand (New mailcommand ()); <br/> $ CC-> runcommand ('adduser', null); <br/> $ CC-> runcommand ('mail', null); <br/>?> <Br/>

 

Rule Mode

 

The last design pattern we talk about is the strategy pattern. In this mode, algorithms are extracted from complex classes and can be easily replaced. For example, if you want to change the page Arrangement Method in the search engine, the policy mode is a good choice. Think about the several parts of the search engine that traverse the page. Some parts are arranged on each page, and the other part is sorted Based on the arranged results. In a complex example, these parts are in the same class. By using the Policy mode, you can place the arranged parts into another class to change the page arrangement method without affecting the rest of the search engine code.

 

 

<? Php <br/> interface istrategy // defines an interface <br/>{< br/> function filter ($ record ); <br/>}</P> <p> class findafterstrategy implements istrategy // inheritance interface <br/>{< br/> private $ _ name; </P> <p> public function _ construct ($ name) <br/>{< br/> $ this-> _ name = $ name; <br/>}</P> <p> Public Function Filter ($ record) <br/>{< br/> return strcmp ($ this-> _ name, $ record) <= 0; // returns the size of two strings <br/>}</P> <p> class R Andomstrategy implements istrategy // random comparison of inherited interfaces <br/>{< br/> Public Function Filter ($ record) <br/>{< br/> return rand (0, 1) >=0.5; <br/>}</P> <p> class userlist <br/>{< br/> private $ _ list = array (); </P> <p> public function _ construct ($ names) // user registration <br/>{< br/> if ($ names! = NULL) <br/>{< br/> foreach ($ names as $ name) <br/>{< br/> $ this-> _ list [] = $ name; <br/>}</P> <p> Public Function add ($ name) <br/>{< br/> $ this-> _ list [] = $ name; <br/>}</P> <p> Public Function find ($ filter) // interface in Rule mode (a method object is passed in) <br/>{< br/> $ RECs = array (); <br/> foreach ($ this-> _ list as $ user) <br/>{< br/> if ($ filter-> filter ($ user )) // compare the passed names with _ names <br/> $ RECs [] = $ User; <br/>}< br/> return $ RECs; <br/>}</P> <p> $ ul = new userlist (Array ("Andy", "Jack", "Lori ", "Megan"); <br/> $ F1 = $ ul-> Find (New findafterstrategy ("J ")); // initialize _ name and assign a value <br/> print_r ($ F1); </P> <p> $ F2 = $ ul-> Find (New randomstrategy ()); <br/> print_r ($ F2); <br/>?> <Br/>

 

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.