Everyone has always had a wrong idea that the design mode is only prepared for the Java architect. In fact, the design pattern is very useful to everyone. Here we will introduce the single element pattern of PHP. After reading this article, you will surely gain a lot.
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. PHP 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 1 shows a single database connection element in PHP V5.
Case study of PHP single element mode:
Listing 1. Singleton. php
- <?php
- require_once("DB.php");
-
- class DatabaseConnection
- {
- public static function get()
- {
- static $db = null;
- if ( $db == null )
- $db = new DatabaseConnection();
- return $db;
- }
-
- private $_handle = null;
-
- private function __construct()
- {
- $dsn = 'mysql://root:password@localhost/photos';
- $this->_handle =& DB::Connect( $dsn, array() );
- }
-
- public function handle()
- {
- return $this->_handle;
- }
- }
-
- print( "Handle = ".DatabaseConnection::get()->handle()."n" );
- print( "Handle = ".DatabaseConnection::get()->handle()."n" );
- ?>
This code displays a single class named DatabaseConnection. You cannot create your own DatabaseConnection because the constructor is dedicated. However, with the static get method, you can obtain only one DatabaseConnection object. In the two calls, the database handle returned by the handle method is the same, which is the best proof. You can run the code in the command line to observe this point.
- % php singleton.php
- Handle = Object id #3
- Handle = Object id #3
- %
The two handles returned are the same object. If you use a single database connection element in the entire application, you can reuse the same handle anywhere. 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.