Php essence php design model

Source: Internet
Author: User
Tags rewind
Php essence php design model

1. select the most appropriate design mode

Nothing is perfect, and no one has ever said that the design model is a perfect solution. Therefore, you can change these patterns to make them more suitable for your work. For some design patterns, they are inherent in the program; for others, you can change their own patterns. Cooperation and collaboration between modes are common. They constitute the foundation of the entire application (at least part.

2. Singleton mode

  1. // The Database class represents our global DB connection

  2. Class Database {
  3. // A static variable to hold our single 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 );

Problem: You cannot create two instances in Singleton mode. you can use Traits to create two different types of instances, but you still cannot create two identical instances (available in registry mode ).

Create two different types of instance code:

  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 );

3. registry mode the registry mode is only a separate global class. when you need it, you can allow the code to retrieve the same instance of an object, you can also create another instance when you need it (the Global instances will be accessed again once required ).

Registry class:

  1. Class Registry {

  2. /**
  3. * @ Var array The store for all of our objects
  4. */
  5. Static private $ _ store = array ();
  6. /**
  7. * Add an object to the registry
  8. *
  9. * If you do not 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 is 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. }

Outside 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 );

Use the Registry table class within the class, and the user does not interact with the Registry.

Sample 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 do 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 );

4. manufacturing objects in factory mode are the same as reinforced concrete with the same name in the industry. Generally, we use the factory mode to initialize specific implementations of the same abstract class or interface.

In general, although the factory mode is rarely used, it is still the most suitable for initializing many variants based on driver installation. For example, different configurations, sessions, or cache storage engines. The biggest value of the factory mode is that it can encapsulate 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. }

5. iteration mode the iteration mode allows us to add the foreach performance to the internal storage data of any object, not just to the public attributes. It overwrites the default foreach behavior and allows us to inject business logic into the loop.

(1) use the 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. }

(2) use the RecursiveIteratorIterator iterator to traverse the array

  1. $ Array = array (

  2. "Hello", // Level 1
  3. Array (
  4. "World" // Level 2
  5. ),
  6. Array (
  7. "How", // Level 2
  8. Array (
  9. "Are", // 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. }

(3) implement filtering with FilterIterator iterator

  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 => "",
  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. ?>

(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. }

Function: find all php files.

(4) LimitItertor iterator, such as LIMIT in SQL

  1. // Define the array

  2. $ Array = array (
  3. 'Hello ',
  4. 'World ',
  5. 'Who ',
  6. 'Are ',
  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. }

6. observer Mode (observer)

The core of the observer mode is that your application registers a callback. when a specific event occurs, it will be promoted.

  1. /**

  2. * The Event Class
  3. *
  4. * With this class you can register callbacks that will
  5. * Be 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 be 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 do not wish to use a closure
  60. * You can define a class that extends
  61. * This instead. The run method will 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

7. Dependency Injection mode: the dependency injection mode allows classes to be used to inject dependencies to 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 );

Dependency injection does not require the factory mode, and does not require knowledge about every different storage engine. This means that any developer who uses the log class can add their own storage engine, and only use their composite interfaces.

8. Model-View-Controller model-view-controller, also known as MVC mode, is a way to describe the relationship between three different layers of an application. Model-all output data at the data layer comes from the model. It may be a database, web service, or file. View-the presentation layer is responsible for extracting and outputting data from the model to the user. Controller-the application stream layer calls the corresponding model based on the user's request to retrieve the requested data, and then calls the view to display the operation results to the user.

A typical MVC architecture diagram:

9. understanding of the model
Mode is the best solution to many common problems.

Articles you may be interested in:
  • Php design pattern Singleton pattern, factory pattern and observer pattern
  • In-depth explanation of php design patterns
  • Php design mode instance command mode
  • Php design pattern example-Observer pattern (2)
  • PHP design pattern instance observer pattern
  • Php design mode instance factory mode
  • Php design pattern instance Singleton pattern
  • Example of observer pattern in PHP design pattern
  • Php design pattern-factory pattern instance code
  • Php design mode-instance code in Singleton mode
  • Common php design modes: Factory mode and Singleton mode
  • Learning php design patterns-Singleton patterns
  • Notes on three common design patterns in php
  • Single-instance learning for php design patterns

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.