Singleton trong PHP

Lại Đình Cường

Tài liệu thiết kế website

Đôi khi bạn muốn tạo 1 class nhưng không cho phép nó được khởi tạo nhiều lần, mà class này chỉ được khởi tạo 1 lần và dùng đi dùng lại thì bạn hãy tìm từ khóa Singleton.

/**
 * The Singleton class defines the `GetInstance` method that serves as an
 * alternative to constructor and lets clients access the same instance of this
 * class over and over.
 */
class Singleton {
    /**
     * The Singleton's instance is stored in a static field. This field is an
     * array, because we'll allow our Singleton to have subclasses. Each item in
     * this array will be an instance of a specific Singleton's subclass. You'll
     * see how this works in a moment.
     */
    private static $instance = null;

    /**
     * The Singleton's constructor should always be private to prevent direct
     * construction calls with the `new` operator.
     */
    protected function __construct() {
    }

    /**
     * Singletons should not be cloneable.
     */
    protected function __clone() {
    }

    /**
     * Singletons should not be restorable from strings.
     */
    public function __wakeup() {
        throw new \Exception( "Cannot unserialize a singleton." );
    }

    /**
     * This is the static method that controls the access to the singleton
     * instance. On the first run, it creates a singleton object and places it
     * into the static field. On subsequent runs, it returns the client existing
     * object stored in the static field.
     *
     * This implementation lets you subclass the Singleton class while keeping
     * just one instance of each subclass around.
     */
    public static function get_instance(): Singleton {
        if ( ! ( self::$instance instanceof self ) ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Finally, any singleton should define some business logic, which can be
     * executed on its instance.
     */
    public function some_function() {
        // ...
    }
}

/**
 * The client code.
 */
function client_call_code() {
    $s1 = Singleton::get_instance();
    $s2 = Singleton::get_instance();

    if ( $s1 === $s2 ) {
        return "Singleton works, both variables contain the same instance.";
    }

    return "Singleton failed, variables contain different instances.";
}

error_log( client_call_code() );

Ok, như vậy bạn không thể khởi tạo new Singleton() cho các biến mà chỉ có thể dùng thông qua hàm Singleton::get_instance(). Dù bạn có gọi bao nhiêu lần thì đối tượng Singleton cũng chỉ là duy nhất.

0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất