1, choose the most suitable design mode Nothing is perfect, and no one has ever said design patterns a strict universal solution. So you can change these patterns to make them more suitable for the job at hand. For some design patterns, they are the innate nature of their own programs, and for some other design patterns you can change their own patterns. It is common that patterns work together with each other. They form the basis for the entire application (at least a portion). 2. Single-case mode
The Database class represents our global DB connection
- Class database{
- A static variable to the instance
- private static $_instance = null;
- Make the constructor private to ensure Singleton
- Private Function __construct ()
- {
- Echo ' constructor ';
- }
A method to get our singleton instance
- public static function getinstance ()
- {
- if (! ( Self::$_instance instanceof Database) {
- Self::$_instance = new Database ();
- }
- return self::$_instance;
- }
- }
$database = Database::getinstance ();
- Var_dump ($database);
Copy CodeProblem: You cannot create two instances using singleton mode, you can solve the problem of creating two different types of instances, but still cannot resolve the problem of creating two identical instances (available with Registry mode resolution). Traits Create an instance code of two different classes:
-
- trait Singleton {
- private static $_instance = null;
-
- public static function getinstance () {
- $class = __class__;
-
- if (! ( Self::$_instance instanceof $class) {
- self::$_instance = new $class;
- }
-
- return self::$_instance;
- }
-
- }
- class DB {
- }
-
- class Dbwriteconnection extends DB {
- use Singleton;
-
- Private Function __construct () {
- echo ' dbwriteconnection
';
- }
- }
-
- class Dbreadconnection extends DB {
- use Singleton;
-
- Private Function __construct () {
- echo ' dbreadconnection
';
- }
- }
-
- $dbWriteConnection = Dbwriteconnection::getinstance ();
- Var_dump ($dbWriteConnection);
Copy Code3. The registry mode registry mode is just a separate global class that allows the code to retrieve the same instance of an object when you need it, or to create another instance when you need it (once again, those global instances are accessed again). Registry class:
Class Registry {
- /**
- * @var array the store for any of our objects
- */
- static Private $_store = Array ();
- /**
- * Add an object to the registry
- *
- * If You don't specify a name the classname is used
- *
- * @param mixed $object the object to store
- * @param string $name name used to retrieve the object
- * @return void
- * @throws Exception
- */
- static public function Add ($object, $name = null)
- {
- Use the classname if no name given, simulates singleton
- $name = (!is_null ($name))? $name: Get_class ($object);
- if (Isset (self::$_store[$name])) {
- throw new Exception ("Object already exists in Registry");
- }
- self::$_store[$name]= $object;
- }
- /**
- * Get an object from the registry
- *
- * @param string $name Object name, {@see self::set ()}
- * @return Mixed
- * @throws Exception
- */
- static public function get ($name)
- {
- if (!self::contains ($name)) {
- throw new Exception ("Object does not exist in Registry");
- }
return self::$_store[$name];
- }
- /**
- * Check If an object was in the registry
- *
- * @param string $name Object name, {@see self::set ()}
- * @return BOOL
- */
- Static public function contains ($name)
- {
- if (!isset (self::$_store[$name])) {
- return false;
- }
- return true;
- }
- /**
- * Remove an object from the registry
- *
- * @param string $name Object name, {@see self::set ()}
- * @returns void
- */
- static public Function Remove ($name)
- {
- if (Self::contains ($name)) {
- Unset (self::$_store[$name]);
- }
- }
- }
Copy CodeOutside of the class, use the registry class:
Require ' registry.php ';
Class Dbreadconnection {}
- Class Dbwriteconnection {}
$read = new Dbreadconnection;
- Registry::add ($read);
$write = new Dbwriteconnection;
- Registry::add ($write);
To get the instances, anywhere in our code:
- $read = Registry::get (' dbreadconnection ');
- $write = Registry::get (' dbwriteconnection ');
Var_dump ($read);
- Var_dump ($write);
Copy CodeUsing the Registry table class inside a class, the consumer does not interact with registry. Example code:
Require ' registry.php ';
Abstract class DBConnection {
- static public Function getinstance ($name = null)
- {
- Get the late-static-binding version of __class__
- $class = Get_called_class ();
- Allow passing in a name to get multiple instances
- If you does not pass a name, it functions as a singleton
- $name = (!is_null ($name))? $name: $class;
- if (! Registry::contains ($name)) {
- $instance = new $class ();
- Registry::add ($instance, $name);
- }
- Return Registry::get ($name);
- }
- }
Class Dbwriteconnection extends DBConnection {
- Public Function __construct ()
- {
- Echo ' Dbwriteconnection
';
- }
- }
Class Dbreadconnection extends DBConnection {
- Public Function __construct ()
- {
- Echo ' Dbreadconnection
';
- }
- }
$dbWriteConnection = dbwriteconnection::getinstance (' abc ');
- Var_dump ($dbWriteConnection);
- $dbReadConnection = Dbreadconnection::getinstance ();
- Var_dump ($dbReadConnection);
Copy Code4. The Factory mode Factory (factory) model is manufactured in the same way as industry with its same name as the reinforced concrete industry. In general, we use the factory pattern to initialize the exact implementation of the same abstract class or interface. In the usual way, although the factory model is rarely used, it is still best suited to initialize many variants based on driver installation. For example, different configurations, sessions, or cache storage engines. The greatest value of the factory pattern is that it encapsulates multiple object settings into a single, simple method call.
- /**
- * Log Factory
- *
- * Setup and return a file, MySQL, or SQLite logger
- */
- Class Log_factory {
- /**
- * Get a Log Object
- *
- * @param string $type The type of logging backend, file, MySQL or SQLite
- * @param array $options Log class options
- */
- Public Function GetLog ($type = ' file ', array $options)
- {
- Normalize the type to lowercase
- $type = Strtolower ($type);
- Figure out the class name and include it
- $class = "Log_". Ucfirst ($type);
- Require_once Str_replace (' _ ', Directory_separator, $class). '. php ';
- Instantiate the class and set the appropriate options
- $log = new $class ($options);
- Switch ($type) {
- Case ' file ':
- $log->setpath ($options [' location ']);
- Break
- Case ' MySQL ':
- $log->setuser ($options [' username ']);
- $log->setpassword ($options [' Password ']);
- $log->setdbname ($options [' location ']);
- Break
- Case ' SQLite ':
- $log->setdbpath ($otions [' location ']);
- Break
- }
- return $log;
- }
- }
Copy Code5. Iterative pattern Iteration patterns allow us to add the performance of foreach to the internal storage of any object, not just to public properties. It overrides the default foreach behavior and allows us to inject business logic into the loop. (1) using the iterator iterator interface
Class Basiciterator implements Iterator {
- Private $key = 0;
- Private $data = Array (
- "Hello",
- "World",
- );
Public Function __construct () {
- $this->key = 0;
- }
Public Function Rewind () {
- $this->key = 0;
- }
Public function current () {
- return $this->data[$this->key];
- }
Public Function key () {
- return $this->key;
- }
Public function next () {
- $this->key++;
- return true;
- }
Public Function valid () {
- return Isset ($this->data[$this->key]);
- }
- }
$iterator = new Basiciterator ();
- $iterator->rewind ();
do {
- $key = $iterator->key ();
- $value = $iterator->current ();
- echo $key. ': ' $value. Php_eol;
- } while ($iterator->next () && $iterator->valid ());
- $iterator = new Basiciterator ();
- foreach ($iterator as $key = = $value) {
- echo $key. ': ' $value. Php_eol;
- }
Copy Code(2) traversing an array using a recursiveiteratoriterator iterator
$array = Array (
- "Hello",//Level 1
- Array
- ' World '//Level 2
- ),
- Array
- ' How ',//Level 2
- Array
- "is",//Level 3
- ' You '//Level 3
- )
- ),
- "Doing?"//Level 1
- );
$recursiveIterator = new Recursivearrayiterator ($array);
$recursiveIteratorIterator = new Recursiveiteratoriterator ($recursiveIterator);
foreach ($recursiveIteratorIterator as $key = = $value) {
- echo "Depth:". $recursiveIteratorIterator->getdepth (). Php_eol;
- echo "Key:". $key. Php_eol;
- echo "Value:". $value. Php_eol;
- }
Copy Code(3) Filtering with Filteriterator iterators
Class Evenfilteriterator extends Filteriterator {
- /**
- * Accept only even-keyed values
- *
- * @return BOOL
- */
- Public Function Accept ()
- {
- Get the actual iterator
- $iterator = $this->getinneriterator ();
- Get the current key
- $key = $iterator->key ();
- Check for even Keys
- if ($key% 2 = = 0) {
- return true;
- }
- return false;
- }
- }
$array = Array (
- 0 = "Hello",
- 1 = "Everybody is",
- 2 = "I ' m",
- 3 = "Amazing",
- 4 = "the",
- 5 = "Who",
- 6 = "Doctor",
- 7 = "Lives"
- );
Create an iterator from our array
- $iterator = new Arrayiterator ($array);
Create our Filteriterator
- $filterIterator = new Evenfilteriterator ($iterator);
Iterate
- foreach ($filterIterator as $key = = $value) {
- echo $key. ': '. $value. Php_eol;
- }
- ?>
Copy Code(4) Regexiterator iterator
Create a Recursivedirectoryiterator
- $directoryIterator = new Recursivedirectoryiterator ("./");
Create a recursiveiteratoriterator to recursively iterate
- $recursiveIterator = new Recursiveiteratoriterator ($directoryIterator);
Createa Filter for *iterator*.php files
- $regexFilter = new Regexiterator ($recursiveIterator, '/(. *?) Iterator (. *?) \.php$/');
Iterate
- foreach ($regexFilter as $key = = $file) {
- /* @var splfileinfo $file */
- echo $file->getfilename (). Php_eol;
- }
Copy CodeFunction: Find all the PHP files (4) Limititertor iterators, like the limit in SQL
Define the array
- $array = Array (
- ' Hello ',
- ' World ',
- ' How ',
- ' Is ',
- ' You ',
- ' doing? '
- );
Create the iterator
- $iterator = new Arrayiterator ($array);
Create the limiting iterator, to get the first 2 elements
- $limitIterator = new Limititerator ($iterator, 0, 2);
Iterate
- foreach ($limitIterator as $key = = $value) {
- echo $key. ': '. $value. Php_eol;
- }
Copy Code6. Observer Mode (Observer) The core of the observer pattern is the sky. Your application registers a callback that will be sent when a particular event occurs
/**
- * The Event Class
- *
- * With this class can register callbacks that would
- * is called (FIFO) for a given event.
- */
- Class Event {
- /**
- * @var array A multi-dimentional array of events = Callbacks
- */
- Static protected $callbacks = Array ();
- /**
- * Register a callback
- *
- * @param string $eventName Name of the triggering event
- * @param mixed $callback An instance of Event_callback or a Closure
- */
- static public Function RegisterCallback ($eventName, $callback)
- {
- if (! ( $callback instanceof event_callback) &&! ($callback instanceof Closure)) {
- throw new Exception ("Invalid callback!");
- }
- $eventName = Strtolower ($eventName);
- Self:: $callbacks [$eventName] = $callback;
- }
- /**
- * Trigger an Event
- *
- * @param string $eventName Name of the event to be triggered
- * @param mixed $data The data to being sent to the callback
- */
- static public Function trigger ($eventName, $data)
- {
- $eventName = Strtolower ($eventName);
- if (Isset (self:: $callbacks [$eventName])) {
- foreach (self:: $callbacks [$eventName] as $callback) {
- Self::callback ($callback, $data);
- }
- }
- }
- /**
- * Perform the callback
- *
- * @param mixed $callback An instance of Event_callback or a Closure
- * @param mixed $data The data sent to the callback
- */
- Static protected function callback ($callback, $data)
- {
- if ($callback instanceof Closure) {
- $callback ($data);
- } else {
- $callback->run ($data);
- }
- }
- }
/**
- * The Event Callback interface
- *
- * If you don't wish to use a closure
- * Can define a class that extends
- * this instead. The Run method would be
- * Called when the event is triggered.
- */
- Interface Event_callback {
- Public function run ($data);
- }
/**
- * Logger Callback
- */
- Class Logcallback implements Event_callback {
- Public function run ($data)
- {
- echo "Log Data". Php_eol;
- Var_dump ($data);
- }
- }
Register the log callback
- Event::registercallback (' Save ', New Logcallback ());
Register the clear cache callback as a closure
- Event::registercallback (' Save ', function ($data) {
- echo "Clear Cache". Php_eol;
- Var_dump ($data);
- });
Class Mydatarecord {
- Public Function Save ()
- {
- Save data
- Trigger the Save Event
- Event::trigger (' Save ', Array ("Hello", "World"));
- }
- }
Instantiate a new data record
- $data = new Mydatarecord ();
- $data->save (); ' Save ' Event is triggered here
Copy Code7. Dependency Injection Mode Dependency Injection mode allows the use of classes this injects dependency behavior into this class.
/**
- * Log Class
- */
- Class Log {
- /**
- * @var Log_engine_interface
- */
- protected $engine = false;
- /**
- * Add an event to the log
- *
- * @param string $message
- */
- Public function Add ($message)
- {
- if (! $this->engine) {
- throw new Exception (' Unable to write log. No Engine set. ');
- }
- $data [' datetime '] = time ();
- $data [' message '] = $message;
- $session = Registry::get (' session ');
- $data [' user '] = $session->getuserid ();
- $this->engine->add ($data);
- }
- /**
- * Set the log data storage engine
- *
- * @param log_engine_interface $Engine
- */
- Public Function Setengine (Log_engine_interface $engine)
- {
- $this->engine = $engine;
- }
- /**
- * Retrieve the data storage engine
- *
- * @return Log_engine_interface
- */
- Public Function Getengine ()
- {
- return $this->engine;
- }
- }
Interface Log_engine_interface {
- /**
- * Add an event to the log
- *
- * @param string $message
- */
- Public function Add (array $data);
- }
Class Log_engine_file implements Log_engine_interface {
- /**
- * Add an event to the log
- *
- * @param string $message
- */
- Public function Add (array $data)
- {
- $line = ' ['. Data (' R ', $data [' datetime ']). '. $data [' message ']. ' User: '. $data [' User ']. Php_eol;
- $config = Registry::get (' Site-config ');
- if (!file_put_contents ($config [' Location '], $line, file_append)) {
- throw new Exception ("An error occurred writing to file.");
- }
- }
- }
$engine = new Log_engine_file ();
$log = new log ();
- $log->setengine ($engine);
ADD it to the registry
- Registry::add ($log);
Copy CodeDependency injection does not want to know about the factory model, the day, or the need to understand every different storage engine. This means that any developer using the log class can add their own storage engine, and the main composite interface will be the line. 8. Model-View-controller model-View-controller, also known as the MVC pattern, is a way to describe the relationship between the 3 different levels of an application. Model-All output data from the data layer is derived from the model. It may be a database, Web service, or file. The view-presentation layer is responsible for extracting the data from the model and outputting it to the user. Controller-the application flow layer invokes the appropriate model to retrieve the requested data based on the user's request, and then invokes the view to display the results of the operation to the user. A typical MVC frame composition: 9. Understanding of the pattern Patterns are the best way to solve many common problems.Articles you may be interested in:
- PHP Design Patterns for Singleton, factory, and observer patterns
- Deep Dive into PHP design pattern examples
- Command mode for PHP design mode instances
- The Observer pattern for PHP design pattern instances (2)
- The Observer pattern for PHP design pattern instances
- The Factory mode of PHP design mode instance
- PHP Design Pattern Example Singleton mode
- Example of the Observer pattern for PHP design Patterns
- Example code for the Factory mode of PHP design mode
- Example code for a singleton pattern in PHP design mode
- Introduction to the Factory mode and singleton mode of PHP common design pattern
- A single-instance model for learning PHP design Patterns
- PHP three common design patterns of learning notes
- PHP design mode for single-instance mode learning
|