Detailed examples of PHP factory mode, singleton mode and registry tree mode

Time:2019-9-11

This paper illustrates PHP factory mode, singleton mode and registration tree mode. Share for your reference, as follows:

Three Basic Design Patterns

1. Factory pattern: Factory method or class generates objects instead of directly new in code
2. Singleton pattern: Allow only one object of a class to be created
3. Registration Mode: Global Sharing and Exchange Objects

Factory model:


<?php
namespace IMooc;
class Factory
{
  static function createDatabase()
  {
    $db = new Database();
    return $db;
  }
}


$db = IMooc\Factory::createDatabase();

The advantage of factory mode is that it avoids the class of database and performs new operations in many PHP files. If there are some changes in the class of database (names or parameters have been changed), then if there are no more changes in the factory mode, we only need to modify the factory method to use the factory mode.

Singleton mode:

<?php
namespace IMooc;
class Database
{
  protected $db;
  private function __construct()
  {
  }
  // Get an instance of database operation
  static function getInstance()
  {
    if(self::$db){
      return self::$db;
    }else{
      self::$db = new self();
      return self::$db;
    }
  }
}
// No matter how many calls are made, only one instance is created.
$db = IMooc\Database::getInstance();
$db = IMooc\Database::getInstance();
$db = IMooc\Database::getInstance();
$db = IMooc\Database::getInstance();

Registry Tree Mode:


<?php
namespace IMooc;
class Register
{
  protected static $objects;
  static function set($alias, $object)
  {
    self::$objects[$alias] = $object;
  }
  static function get($name)
  {
    return self::$objects[$name];
  }
  static function _unset($alias)
  {
    unset(self::$objects[$alias]);
  }
}
$db = \IMooc\Register::get('db1');

More readers interested in PHP-related content can see the topics of this site: Introduction to Php Object-Oriented Programming, Introduction to PHP Array Operating Skills, Introduction to PHP Basic Grammar, Summary of PHP Operating and Operator Usage, Summary of Php String Usage, and php+mysql Data. Introduction to Library Operations and Summary of Common Database Operating Skills in PHP

I hope this article will be helpful to everyone’s PHP program design.