PHP design mode

Source: Internet
Author: User
Tags zend framework

1. Single-case mode

The singleton pattern, as its name implies, is only one instance. As an object's creation mode, Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole.

The main points of the singleton pattern are three:

    1. One is that a class can have only one instance;
    2. The second is that it must create this instance on its own;
    3. Thirdly, it must provide this instance to the whole system on its own.
Why use PHP singleton mode
    1. 1. The application of PHP is mainly in the database application, there will be a large number of database operations in an application, when the use of object-oriented development, if the use of Singleton mode, you can avoid a large number of new operations consumed by the resources, but also reduce the database connection so it is not easy to appear too many Connections situation.
    2. 2. If a class is needed in the system to control some configuration information globally, it can be easily implemented using singleton mode. This can be see the Frontcontroller section of the Zend Framework.
    3. 3. In a page request, it is easy to debug, because all the code (such as database Operation class DB) is concentrated in a class, we can set the hooks in the class, output the log, so as to avoid var_dump everywhere, echo.

Example:

/**
* Design pattern of a single case mode
* $_instance must be declared as a static private variable
* Constructors must be declared private to prevent the external program new class from losing the meaning of a singleton pattern
* The getinstance () method must be set to public, and this method must be called to return a reference to the instance
*:: operator can only access static variables and static functions
* New objects will consume memory
* Usage Scenario: The most common place is the database connection.
* Once an object is generated using singleton mode, the object can be used by many other objects.
*/
Class Mans
{
Save example instance in this property
private static $_instance;

The constructor is declared private, preventing the object from being created directly
Private Function __construct ()
{
Echo ' I was instantiated! ‘;
}

Single Case method
public static function Get_instance ()
{
Var_dump (Isset (self::$_instance));

if (!isset (self::$_instance))
{
Self::$_instance=new self ();
}
return self::$_instance;
}

Prevent users from replicating object instances
Private Function __clone ()
{
Trigger_error (' Clone is not allow ', e_user_error);
}

function test ()
{
Echo ("Test");

}
}

This is an error because the constructor method is declared as private.
$test = new Man;

The following will get the singleton object of the example class
$test = Man::get_instance ();
$test = Man::get_instance ();
$test->test ();

Copying an object will result in a e_user_error.
$test _clone = Clone $test;

2. Simple Factory mode
    • ① abstract base class: Some methods of defining abstractions in classes to implement in subclasses
    • ② inherits from the subclass of the abstract base class: Implementing an abstract method in a base class
    • ③ Factory class: Used to instantiate all the corresponding sub-classes


/**
*
* Define an abstract class that allows subclasses to inherit and implement it
*
*/
Abstract class operation{
Abstract methods cannot contain function bodies
Abstract public Function GetValue ($num 1, $num 2);//strongly require subclasses to implement the function function
}



/**
* Addition class
*/
Class Operationadd extends Operation {
Public Function GetValue ($num 1, $num 2) {
return $num 1+ $num 2;
}
}
/**
* Subtraction Class
*/
Class Operationsub extends Operation {
Public Function GetValue ($num 1, $num 2) {
Return $num 1-$num 2;
}
}
/**
* Multiplication Class
*/
Class Operationmul extends Operation {
Public Function GetValue ($num 1, $num 2) {
return $num 1* $num 2;
}
}
/**
* Division Class
*/
Class Operationdiv extends Operation {
Public Function GetValue ($num 1, $num 2) {
try {
if ($num 2==0) {
throw new Exception ("divisor cannot be 0");
}else {
return $num 1/$num 2;
}
}catch (Exception $e) {
echo "error message:". $e->getmessage ();
}
}
}

by using object-oriented inheritance, we can easily extend the original program, such as: ' exponentiation ', ' root ', ' log ', ' trigonometric ', ' statistics ' and so on, so that you can also avoid loading unnecessary code.

If we need to add a redundancy class now, it will be very simple.

We only need to write another class (the class inherits the virtual base class), in the class to complete the corresponding functions (such as: exponentiation), and greatly reduce the coupling degree, convenient for future maintenance and expansion

/**
* Seeking remainder class (remainder)
*
*/
Class Operationrem extends Operation {
Public Function GetValue ($num 1, $num 2) {
return $num 1% $num 12;
}
}

now there is one more question unresolved, that is, how can the program instantiate the corresponding object according to the user input operator?
Workaround: Use a separate class to implement the instantiation process, which is the factory

/**
* Engineering class, mainly used to create objects
* Function: According to the input operation symbol, the factory can instantiate the suitable object
*
*/
Class factory{
public static function Createobj ($operate) {
Switch ($operate) {
Case ' + ':
return new Operationadd ();
Break
Case '-':
return new Operationsub ();
Break
Case ' * ':
return new Operationsub ();
Break
Case '/':
return new Operationdiv ();
Break
}
}
}
$test =factory::createobj ('/');
$result = $test->getvalue (23,0);
echo $result;

Other notes on this pattern:

Factory mode:
Take the transportation as an example: request to be able to customize the transportation, but also can customize the transportation production process
1> Custom Transportation
1. Define an interface containing the method of the completion tool (Start Operation stop)

2. Let aircraft, cars and other classes to achieve their
2> Custom-made factory (on-site similar)
1. Define an interface containing the manufacturing method of the completion tool (start-up operation stop)

2. Write the manufacturing aircraft, the car factory class to inherit the implementation of this interface

Original address: http://bbs.phpchina.com/thread-242243-1-1.html

3. Observer Mode

The Observer pattern is a behavior pattern, which defines a one-to-many dependency between objects, so that when an object's state changes, all objects that depend on it are notified and refreshed automatically. It perfectly separates the observer object from the object being observed. You can maintain a list of dependencies (observers) that are of interest to the principal in a stand-alone object (body). Let all observers implement a common Observer interface to remove the direct dependencies between the principal and the dependent objects. (I can't understand it anyway)

Use of SPL (Standard PHP library)

Class MyObserver1 implements Splobserver {
Public Function Update (Splsubject $subject) {
Echo __class__. ‘ - ‘ . $subject->getname ();
}
}

Class MyObserver2 implements Splobserver {
Public Function Update (Splsubject $subject) {
Echo __class__. ‘ - ‘ . $subject->getname ();
}
}

Class Mysubject implements Splsubject {
Private $_observers;
Private $_name;

Public function __construct ($name) {
$this->_observers = new Splobjectstorage ();
$this->_name = $name;
}

Public function Attach (Splobserver $observer) {
$this->_observers->attach ($observer);
}

Public Function Detach (Splobserver $observer) {
$this->_observers->detach ($observer);
}

Public Function notify () {
foreach ($this->_observers as $observer) {
$observer->update ($this);
}
}

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

$observer 1 = new MyObserver1 ();
$observer 2 = new MyObserver2 ();

$subject = new Mysubject ("test");

$subject->attach ($observer 1);
$subject->attach ($observer 2);

$subject->notify ();

Reference Original: http://www.php.net/manual/zh/class.splsubject.php

4. Policy mode

In this mode, the algorithm is extracted from the complex class and can therefore be easily replaced. For example, if you want to change the way a page is arranged in a search engine, the policy mode is a good choice. Think about several parts of the search engine--part of the traversal page, one for each page, and one for the sorted results. In a complex example, these parts are in the same class. By using the policy mode, you can put the arrangement part in another class to change the way the page is arranged without affecting the rest of the search engine's code.

As a simpler example, the following shows a user list class that provides a way to find a group of users based on a set of Plug and Play policies

Defining interfaces
Interface IStrategy {
function filter ($record);
}

Implementing interface Mode 1
Class Findafterstrategy implements IStrategy {
Private $_name;
Public function __construct ($name) {
$this->_name = $name;
}
Public Function Filter ($record) {
Return strcmp ($this->_name, $record) <= 0;
}
}

Implementing interface Mode 1
Class Randomstrategy implements IStrategy {
Public Function Filter ($record) {
Return rand (0, 1) >= 0.5;
}
}

Main class
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"
) );
$f 1 = $ul->find (new Findafterstrategy ("J"));
Print_r ($f 1);

$f 2 = $ul->find (new Randomstrategy ());

Print_r ($f 2);

The strategy model is ideal for complex data management systems, or for data processing systems, which require greater flexibility in the way they are filtered, searched, or processed

PHP design mode

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.