A single mode of introduction to PHP design Patterns

Source: Internet
Author: User
Tags mathematical constants php error

In almost all object-oriented programs, there are one or two of resources that are created to be shared and used consistently in program applications. For example, such a resource is used in a database connection of an e-business program: The connection is initialized at the time the application is started, and the program is executed efficiently, and when the program ends, the connection is eventually disconnected and destroyed. If you write the code, there is no need to create a database connection every moment, which is very inefficient. Already established connections should be used simply and repeatedly by your code. The question is, how will you make this database connection based on the above requirements? (or to connect to other unique resources that are recycled, such as an open file or a queue.) )

Problem

How do you make sure that an instance of a particular class is unique (it is the only instance of the class) and that it is easy to access?

Solution

Of course, global variables are the obvious solution. But it's like Pandora's Box (the right judgment comes from experience, and wrong judgments produce experience.) That's what the proverb means. , any of your code can modify global variables, which will inevitably cause more debugging surprises. In other words, there are always problems with the state of a global variable (here's a good description of the global variable usage problem, Http://c2.com/cgi/wiki?GlobalVariablesAreBad).

When you need a unique instance of a particular class, use this name as a single piece of mode. A class based on a single piece pattern can instantiate and initialize an instance of this class, and provide an absolutely identical connection every moment. Typically, a static method named GetInstance () is implemented.

The key question is how to get a precise and unified example at every moment. Take a look at the following example:

PHP4

function TestGetInstance() {
$this->assertIsA(
$obj1 =& DbConn::getInstance(),
‘DbConn’,
‘The returned object is an instance of DbConn’);
$this->assertReference(
$obj1,
$obj2 =& DbConn::getInstance(),
‘Two calls to getInstance() return the same object’);
}

Note: assertreference

The Assertreference () method ensures that two parameters that are passed are referenced from the same PHP variable.

In PHP4, it is asserted that two of the parameters tested are the same object. Assertreference () This method may be deprecated after porting to PHP5.

This test method has two assertions: the first to determine that the value returned by the call to the static method Dbconn::getinstance () is an instance of the Dbconn object, and the second is used to determine that the second call to the getinstance () method returns a value that references the same object instance. This means that they are using the same object.

In addition to asserting the expected execution of the code, test also predicts the correct use of getinstance (PHP4): $local _conn_var=&dbconn::getinstance (). The return value of a reference (=&) static method is assigned to this local variable.

Write another section of the test code: instantiating a single piece class directly with "new" can cause some type of error. The test code is as follows:

function TestBadInstantiate() {
$obj =& new DbConn;
$this->assertErrorPattern(
‘/(bad|nasty|evil|do not|don\’t|warn).*’.
‘(instance|create|new|direct)/i’);
}

This code directly creates a Dbconn instance that will cause a PHP error. To make the code more stable, we use pcre regular expressions to match the error message. (The exact wording that displays the error message is not important.) )

Sample code

Single-piece mode is a very interesting pattern. Let's explore its implementation with PHP4 and PHP5 two ways, now starting with PHP4.

Global Approach

In theory, a global variable can produce a perfect single piece, but a global variable can be modified: it is not guaranteed that the global variable points to an object while the code is running. Therefore, you can reduce the problem of "too random Access" global variables by not having global variables directly referenced globally. For example, this code uses a very long and unique name to "hide" the reference to a global variable.

class DbConn {
function DbConn($fromGetInstance=false) {
if (M_E != $fromGetInstance) {
trigger_error (‘The DbConn class is a Singleton,’
.’ please do not instantiate directly.’);
}
}
function &getInstance() {
$key = ‘__some_unique_key_for_the_DbConn_instance__’;
if (!(array_key_exists ($key, $GLOBALS) && is_object($GLOBALS[$key])
&& ‘dbconn’ == get_class($GLOBALS[$key]) )) {
$GLOBALS[$key] =& new DbConn(M_E);
}
return $GLOBALS[$key];
}
}

In the Dbconn constructor, you may be puzzled by the default parameters for $fromGetInstance. When an object is directly instantiated, it can provide (very faint) protection: Unless the default value becomes E (m_e = 2.718281828459 in the mathematical constants of PHP), this code will complain.

represented as a UML class diagram, the solution is as follows:

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.