PHP Pristine PHP design mode

Source: Internet
Author: User

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

    1. The Database class represents our global DB connection

    2. Class database{
    3. A static variable to the instance
    4. private static $_instance = null;
    5. Make the constructor private to ensure Singleton
    6. Private Function __construct ()
    7. {
    8. Echo ' constructor ';
    9. }

    10. A method to get our singleton instance

    11. public static function getinstance ()
    12. {
    13. if (! ( Self::$_instance instanceof Database) {
    14. Self::$_instance = new Database ();
    15. }
    16. return self::$_instance;
    17. }
    18. }

    19. $database = Database::getinstance ();

    20. Var_dump ($database);

Copy Code

Problem: 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:

    1. trait Singleton {
    2. private static $_instance = null;
    3. public static function getinstance () {
    4. $class = __class__;
    5. if (! ( Self::$_instance instanceof $class) {
    6. self::$_instance = new $class;
    7. }
    8. return self::$_instance;
    9. }
    10. }
    11. class DB {
    12. }
    13. class Dbwriteconnection extends DB {
    14. use Singleton;
    15. Private Function __construct () {
    16. echo ' dbwriteconnection
      ';
    17. }
    18. }
    19. class Dbreadconnection extends DB {
    20. use Singleton;
    21. Private Function __construct () {
    22. echo ' dbreadconnection
      ';
    23. }
    24. }
    25. $dbWriteConnection = Dbwriteconnection::getinstance ();
    26. Var_dump ($dbWriteConnection);
Copy Code

3. 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:

  1. Class Registry {

  2. /**
  3. * @var array the store for any of our objects
  4. */
  5. static Private $_store = Array ();
  6. /**
  7. * Add an object to the registry
  8. *
  9. * If You don't specify a name the classname is used
  10. *
  11. * @param mixed $object the object to store
  12. * @param string $name name used to retrieve the object
  13. * @return void
  14. * @throws Exception
  15. */
  16. static public function Add ($object, $name = null)
  17. {
  18. Use the classname if no name given, simulates singleton
  19. $name = (!is_null ($name))? $name: Get_class ($object);
  20. if (Isset (self::$_store[$name])) {
  21. throw new Exception ("Object already exists in Registry");
  22. }
  23. self::$_store[$name]= $object;
  24. }
  25. /**
  26. * Get an object from the registry
  27. *
  28. * @param string $name Object name, {@see self::set ()}
  29. * @return Mixed
  30. * @throws Exception
  31. */
  32. static public function get ($name)
  33. {
  34. if (!self::contains ($name)) {
  35. throw new Exception ("Object does not exist in Registry");
  36. }

  37. return self::$_store[$name];

  38. }
  39. /**
  40. * Check If an object was in the registry
  41. *
  42. * @param string $name Object name, {@see self::set ()}
  43. * @return BOOL
  44. */
  45. Static public function contains ($name)
  46. {
  47. if (!isset (self::$_store[$name])) {
  48. return false;
  49. }
  50. return true;
  51. }
  52. /**
  53. * Remove an object from the registry
  54. *
  55. * @param string $name Object name, {@see self::set ()}
  56. * @returns void
  57. */
  58. static public Function Remove ($name)
  59. {
  60. if (Self::contains ($name)) {
  61. Unset (self::$_store[$name]);
  62. }
  63. }
  64. }
Copy Code

Outside of the class, use the registry class:

    1. Require ' registry.php ';

    2. Class Dbreadconnection {}

    3. Class Dbwriteconnection {}

    4. $read = new Dbreadconnection;

    5. Registry::add ($read);

    6. $write = new Dbwriteconnection;

    7. Registry::add ($write);

    8. To get the instances, anywhere in our code:

    9. $read = Registry::get (' dbreadconnection ');
    10. $write = Registry::get (' dbwriteconnection ');

    11. Var_dump ($read);

    12. Var_dump ($write);
Copy Code

Using the Registry table class inside a class, the consumer does not interact with registry.

Example code:

  1. Require ' registry.php ';

  2. Abstract class DBConnection {

  3. static public Function getinstance ($name = null)
  4. {
  5. Get the late-static-binding version of __class__
  6. $class = Get_called_class ();
  7. Allow passing in a name to get multiple instances
  8. If you does not pass a name, it functions as a singleton
  9. $name = (!is_null ($name))? $name: $class;
  10. if (! Registry::contains ($name)) {
  11. $instance = new $class ();
  12. Registry::add ($instance, $name);
  13. }
  14. Return Registry::get ($name);
  15. }
  16. }

  17. Class Dbwriteconnection extends DBConnection {

  18. Public Function __construct ()
  19. {
  20. Echo ' Dbwriteconnection
    ';
  21. }
  22. }

  23. Class Dbreadconnection extends DBConnection {

  24. Public Function __construct ()
  25. {
  26. Echo ' Dbreadconnection
    ';
  27. }
  28. }

  29. $dbWriteConnection = dbwriteconnection::getinstance (' abc ');

  30. Var_dump ($dbWriteConnection);
  31. $dbReadConnection = Dbreadconnection::getinstance ();
  32. Var_dump ($dbReadConnection);

Copy Code

4. 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.

  1. /**
  2. * Log Factory
  3. *
  4. * Setup and return a file, MySQL, or SQLite logger
  5. */
  6. Class Log_factory {
  7. /**
  8. * Get a Log Object
  9. *
  10. * @param string $type The type of logging backend, file, MySQL or SQLite
  11. * @param array $options Log class options
  12. */
  13. Public Function GetLog ($type = ' file ', array $options)
  14. {
  15. Normalize the type to lowercase
  16. $type = Strtolower ($type);
  17. Figure out the class name and include it
  18. $class = "Log_". Ucfirst ($type);
  19. Require_once Str_replace (' _ ', Directory_separator, $class). '. php ';
  20. Instantiate the class and set the appropriate options
  21. $log = new $class ($options);
  22. Switch ($type) {
  23. Case ' file ':
  24. $log->setpath ($options [' location ']);
  25. Break
  26. Case ' MySQL ':
  27. $log->setuser ($options [' username ']);
  28. $log->setpassword ($options [' Password ']);
  29. $log->setdbname ($options [' location ']);
  30. Break
  31. Case ' SQLite ':
  32. $log->setdbpath ($otions [' location ']);
  33. Break
  34. }
  35. return $log;
  36. }
  37. }
Copy Code

5. 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

  1. Class Basiciterator implements Iterator {

  2. Private $key = 0;
  3. Private $data = Array (
  4. "Hello",
  5. "World",
  6. );

  7. Public Function __construct () {

  8. $this->key = 0;
  9. }

  10. Public Function Rewind () {

  11. $this->key = 0;
  12. }

  13. Public function current () {

  14. return $this->data[$this->key];
  15. }

  16. Public Function key () {

  17. return $this->key;
  18. }

  19. Public function next () {

  20. $this->key++;
  21. return true;
  22. }

  23. Public Function valid () {

  24. return Isset ($this->data[$this->key]);
  25. }
  26. }

  27. $iterator = new Basiciterator ();

  28. $iterator->rewind ();

  29. do {

  30. $key = $iterator->key ();
  31. $value = $iterator->current ();
  32. echo $key. ': ' $value. Php_eol;
  33. } while ($iterator->next () && $iterator->valid ());

  34. $iterator = new Basiciterator ();
  35. foreach ($iterator as $key = = $value) {
  36. echo $key. ': ' $value. Php_eol;
  37. }

Copy Code

(2) traversing an array using a recursiveiteratoriterator iterator

    1. $array = Array (

    2. "Hello",//Level 1
    3. Array
    4. ' World '//Level 2
    5. ),
    6. Array
    7. ' How ',//Level 2
    8. Array
    9. "is",//Level 3
    10. ' You '//Level 3
    11. )
    12. ),
    13. "Doing?"//Level 1
    14. );

    15. $recursiveIterator = new Recursivearrayiterator ($array);

    16. $recursiveIteratorIterator = new Recursiveiteratoriterator ($recursiveIterator);

    17. foreach ($recursiveIteratorIterator as $key = = $value) {

    18. echo "Depth:". $recursiveIteratorIterator->getdepth (). Php_eol;
    19. echo "Key:". $key. Php_eol;
    20. echo "Value:". $value. Php_eol;
    21. }

Copy Code

(3) Filtering with Filteriterator iterators

  1. Class Evenfilteriterator extends Filteriterator {

  2. /**
  3. * Accept only even-keyed values
  4. *
  5. * @return BOOL
  6. */
  7. Public Function Accept ()
  8. {
  9. Get the actual iterator
  10. $iterator = $this->getinneriterator ();
  11. Get the current key
  12. $key = $iterator->key ();
  13. Check for even Keys
  14. if ($key% 2 = = 0) {
  15. return true;
  16. }
  17. return false;
  18. }
  19. }

  20. $array = Array (

  21. 0 = "Hello",
  22. 1 = "Everybody is",
  23. 2 = "I ' m",
  24. 3 = "Amazing",
  25. 4 = "the",
  26. 5 = "Who",
  27. 6 = "Doctor",
  28. 7 = "Lives"
  29. );

  30. Create an iterator from our array

  31. $iterator = new Arrayiterator ($array);

  32. Create our Filteriterator

  33. $filterIterator = new Evenfilteriterator ($iterator);

  34. Iterate

  35. foreach ($filterIterator as $key = = $value) {
  36. echo $key. ': '. $value. Php_eol;
  37. }
  38. ?>

Copy Code

(4) Regexiterator iterator

    1. Create a Recursivedirectoryiterator

    2. $directoryIterator = new Recursivedirectoryiterator ("./");

    3. Create a recursiveiteratoriterator to recursively iterate

    4. $recursiveIterator = new Recursiveiteratoriterator ($directoryIterator);

    5. Createa Filter for *iterator*.php files

    6. $regexFilter = new Regexiterator ($recursiveIterator, '/(. *?) Iterator (. *?) \.php$/');

    7. Iterate

    8. foreach ($regexFilter as $key = = $file) {
    9. /* @var splfileinfo $file */
    10. echo $file->getfilename (). Php_eol;
    11. }
Copy Code

Function: Find all the PHP files

(4) Limititertor iterators, like the limit in SQL

    1. Define the array

    2. $array = Array (
    3. ' Hello ',
    4. ' World ',
    5. ' How ',
    6. ' Is ',
    7. ' You ',
    8. ' doing? '
    9. );

    10. Create the iterator

    11. $iterator = new Arrayiterator ($array);

    12. Create the limiting iterator, to get the first 2 elements

    13. $limitIterator = new Limititerator ($iterator, 0, 2);

    14. Iterate

    15. foreach ($limitIterator as $key = = $value) {
    16. echo $key. ': '. $value. Php_eol;
    17. }

Copy Code

6. 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

  1. /**

  2. * The Event Class
  3. *
  4. * With this class can register callbacks that would
  5. * is called (FIFO) for a given event.
  6. */
  7. Class Event {
  8. /**
  9. * @var array A multi-dimentional array of events = Callbacks
  10. */
  11. Static protected $callbacks = Array ();
  12. /**
  13. * Register a callback
  14. *
  15. * @param string $eventName Name of the triggering event
  16. * @param mixed $callback An instance of Event_callback or a Closure
  17. */
  18. static public Function RegisterCallback ($eventName, $callback)
  19. {
  20. if (! ( $callback instanceof event_callback) &&! ($callback instanceof Closure)) {
  21. throw new Exception ("Invalid callback!");
  22. }
  23. $eventName = Strtolower ($eventName);
  24. Self:: $callbacks [$eventName] = $callback;
  25. }
  26. /**
  27. * Trigger an Event
  28. *
  29. * @param string $eventName Name of the event to be triggered
  30. * @param mixed $data The data to being sent to the callback
  31. */
  32. static public Function trigger ($eventName, $data)
  33. {
  34. $eventName = Strtolower ($eventName);
  35. if (Isset (self:: $callbacks [$eventName])) {
  36. foreach (self:: $callbacks [$eventName] as $callback) {
  37. Self::callback ($callback, $data);
  38. }
  39. }
  40. }
  41. /**
  42. * Perform the callback
  43. *
  44. * @param mixed $callback An instance of Event_callback or a Closure
  45. * @param mixed $data The data sent to the callback
  46. */
  47. Static protected function callback ($callback, $data)
  48. {
  49. if ($callback instanceof Closure) {
  50. $callback ($data);
  51. } else {
  52. $callback->run ($data);
  53. }
  54. }
  55. }

  56. /**

  57. * The Event Callback interface
  58. *
  59. * If you don't wish to use a closure
  60. * Can define a class that extends
  61. * this instead. The Run method would be
  62. * Called when the event is triggered.
  63. */
  64. Interface Event_callback {
  65. Public function run ($data);
  66. }

  67. /**

  68. * Logger Callback
  69. */
  70. Class Logcallback implements Event_callback {
  71. Public function run ($data)
  72. {
  73. echo "Log Data". Php_eol;
  74. Var_dump ($data);
  75. }
  76. }

  77. Register the log callback

  78. Event::registercallback (' Save ', New Logcallback ());

  79. Register the clear cache callback as a closure

  80. Event::registercallback (' Save ', function ($data) {
  81. echo "Clear Cache". Php_eol;
  82. Var_dump ($data);
  83. });

  84. Class Mydatarecord {

  85. Public Function Save ()
  86. {
  87. Save data
  88. Trigger the Save Event
  89. Event::trigger (' Save ', Array ("Hello", "World"));
  90. }
  91. }

  92. Instantiate a new data record

  93. $data = new Mydatarecord ();
  94. $data->save (); ' Save ' Event is triggered here

Copy Code

7. Dependency Injection Mode Dependency Injection mode allows the use of classes this injects dependency behavior into this class.

  1. /**

  2. * Log Class
  3. */
  4. Class Log {
  5. /**
  6. * @var Log_engine_interface
  7. */
  8. protected $engine = false;
  9. /**
  10. * Add an event to the log
  11. *
  12. * @param string $message
  13. */
  14. Public function Add ($message)
  15. {
  16. if (! $this->engine) {
  17. throw new Exception (' Unable to write log. No Engine set. ');
  18. }
  19. $data [' datetime '] = time ();
  20. $data [' message '] = $message;
  21. $session = Registry::get (' session ');
  22. $data [' user '] = $session->getuserid ();
  23. $this->engine->add ($data);
  24. }
  25. /**
  26. * Set the log data storage engine
  27. *
  28. * @param log_engine_interface $Engine
  29. */
  30. Public Function Setengine (Log_engine_interface $engine)
  31. {
  32. $this->engine = $engine;
  33. }
  34. /**
  35. * Retrieve the data storage engine
  36. *
  37. * @return Log_engine_interface
  38. */
  39. Public Function Getengine ()
  40. {
  41. return $this->engine;
  42. }
  43. }

  44. Interface Log_engine_interface {

  45. /**
  46. * Add an event to the log
  47. *
  48. * @param string $message
  49. */
  50. Public function Add (array $data);
  51. }

  52. Class Log_engine_file implements Log_engine_interface {

  53. /**
  54. * Add an event to the log
  55. *
  56. * @param string $message
  57. */
  58. Public function Add (array $data)
  59. {
  60. $line = ' ['. Data (' R ', $data [' datetime ']). '. $data [' message ']. ' User: '. $data [' User ']. Php_eol;
  61. $config = Registry::get (' Site-config ');
  62. if (!file_put_contents ($config [' Location '], $line, file_append)) {
  63. throw new Exception ("An error occurred writing to file.");
  64. }
  65. }
  66. }

  67. $engine = new Log_engine_file ();

  68. $log = new log ();

  69. $log->setengine ($engine);

  70. ADD it to the registry

  71. Registry::add ($log);

Copy Code

Dependency 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
  • 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.