Detail the three classic modes in PHP

Singleton mode

The meaning of the singleton pattern:
As an object creation mode, the singleton mode ensures that a class has only one instance and instantiates itself and provides this instance to the entire system globally.Instead of creating a copy of the instance, it returns a reference to the instance stored inside the singleton class.
Three elements of the singleton pattern:
1. Save static variables for unique instances of classes.(
2. Constructors and clones must be private and externally de-instantiated so that there is no meaning for the singleton pattern.(
3. Provide a public static method that can be accessed externally that returns a unique instance of the class.
Significance of the singleton pattern:
The applications in PHP are mainly database applications, so there are a lot of database operations in one application. When developing in an object-oriented way, using the singleton mode can avoid a lot of resources consumed by the new operation.Rather than saving system resources entirely, you can avoid duplicate instantiations because PHP cleans up the corresponding resources after each instantiation of a class and re-instantiates them when reused.
Scenarios used in the singleton mode:
1. Database operations to reduce new operations on data paths, thereby reducing the consumption of memory and system resources.(
2. The sharing of configuration resources. In a system, the configuration resources are global, and the use of singleton mode can also reduce the consumption of memory and system resources each time the configuration is read.
Code demonstration:

<?php
class Single
{
    public static $attribute = '';
    public static $instance = '';
    private function __construct($attribute = 'Personal Technology')
    {
        self::$attribute = $attribute;
    }
    public static function getInstance($attribute = 'I am a programming prodigal.')
    {
        if (!(self::$instance instanceof self)) self::$instance = new self($attribute);
        return self::$instance;
    }
}

Differences between singleton and non-singleton modes:

class Single {
    public function index() {
        return '';
    }
}
$single1 = new Single();
$single2 = new Single();
var_dump($single1);
var_dump($single2);
if ($single2 === $single1) {
    echo "Is the same object";
} else {
    echo "Not the same object";
}
// object(Single)#1 (0) {
// }
// object(Single)#2 (0) {
// }
//Not the same object
class Single2 {
    //1. Declare a static property and the user saves an instance of the class
    public static $instance;
    //3. Privateize the constructor to avoid external new (every new is not the same instance)
    private function __construct() {
    }
    //2. Declare a static public method that the user calls an instance of this class externally
    public static function getInstance() {
        if (!(self::$instance instanceof self)) {
            self::$instance = new self;
        }
        return self::$instance;
    }
    //3. Privatize clone functions to avoid external clones (not the same instance every clone)
    private function __clone() {
    }
}
$singleDemo1 = Single2::getInstance();
$singleDemo2 = Single2::getInstance();
var_dump($singleDemo1->getInstance());
var_dump($singleDemo2->getInstance());
if ($singleDemo1 === $singleDemo2) {
    echo "Is the same object";
} else {
    echo "Not the same object";
}
// object(Single2)#3 (0) {
// }
// object(Single2)#3 (0) {
// }
//Is the same object

Factory Mode

What factory mode means:
The method responsible for generating other objects.A simple description is to instantiate another class or method through a factory class.
Meaning of factory mode:
Reduce by using factory mode because more than one new class is the same, and when this class changes, more than one modification is required.
Code demonstration:

<?php
class Factor
{
    public static function createDB()
    {
        echo 'I produced one DB Example';
        return new DB;
    }
}
class DB
{
    public function __construct()
    {
        echo __CLASS__ . PHP_EOL;
    }
}
$db = Factor::createDB();

Register Tree Mode

The meaning of the number of registrations:
Registering a tree means registering multiple objects in one object pool, which can be obtained directly from the object pool when we need to use it.

Advantages of registered number mode:
The singleton pattern solves the problem of how to create a unique instance of an object throughout the project, and the factory pattern solves the problem of how to create an instance object without using new.What is the problem registered tree mode is trying to solve?Before considering this issue, it is necessary to consider the limitations of the first two modes.First, the process of creating a unique object in a singleton pattern has its own judgment, that is, whether the object exists or not.An object is returned if it exists, and an object is created and returned if it does not exist.This level of judgment exists every time an instance object is created.The factory model considers extended maintenance more.Overall, the singleton and factory models can produce more reasonable objects.How can I call these objects easily?What's more, it's inconvenient to make overall management arrangements for the objects so established in the project like scattered soldiers.As a result, the Registered Tree mode has emerged.Whether you're using singleton mode or factory mode or a combination of the two, they all "plug" me into the registration tree.When I use an object, I just grab it from the registration tree.This is as convenient and useful as using global variables.And the Registered Tree mode provides a great idea for other modes.
Code demonstration:

<?ph
/**
 * Singleton mode
 */
class Single
{
    public static $attribute = '';
    public static $instance = '';
    private function __construct($attribute = 'Personal Technology')
    {
        self::$attribute = $attribute;
    }
    public static function getInstance($attribute = 'Personal Technology 1')
    {
        if (!(self::$instance instanceof self)) self::$instance = new self($attribute);
        return self::$instance;
    }
}
/**
 * Factory Mode
 */
class Factory
{
    public static function createObj()
    {
        return Single::getInstance('Personal Technology');
    }
}
/**

 * Registration mode

 * Meaning: Place the object in an object pool and go directly to the object pool when using it.

 * The following actions are required:

 * 1.register

 * 2.Storage object pool

 * 3.Obtain

 * 4.Destroy

 */
Class Register
{
    //Use an array as an object pool, keys as object aliases, and values to store specific objects
    public static $objTree = [];
    //Put Objects in Object Pool
    public static function set($key, $val)
    {
        return self::$objTree[$key] = $val;
    }
    //Obtain object aliases in object pool by object aliases
    public static function get($key)
    {
        return self::$objTree[$key];
    }
    //Unregister object from object pool by object alias
    public static function _unset($key)
    {
        unset(self::$objTree[$key]);
    }
}
Register::set('single', Factory::createObj());
$single = Register::get('single');
print_r($single);
echo $single::$attribute;

This article is from WeChat Public Number Talk late at night Release!

Tags: PHP Attribute Database Programming

Posted on Thu, 07 Nov 2019 13:20:24 -0500 by gabeg