Home Backend Development PHP Tutorial [Design Pattern] Application scenarios and implementation of PHP singleton pattern

[Design Pattern] Application scenarios and implementation of PHP singleton pattern

Jun 02, 2020 am 12:58 AM
Singleton pattern

Summary

What is the singleton pattern?

A class is only allowed to create one object (or instance), then this class is a singleton class. This design pattern is called the singleton design pattern, or singleton pattern for short.

Why use singleton?

  1. # Handle resource access conflicts.

    For example: the function of printing logs to a file.

  2. represents a globally unique class.

From a business concept, if some data should only be saved in one copy in the system, it is more suitable to design it as a singleton class. For example: unique increasing ID number generator.

Implementation method

It takes three steps to implement the singleton mode of PHP

* A static member variable used to save the class.

* To prevent object creation or cloning, __construct and __clone need to be declared private.

* A public static method to access this instance, usually getInstance

class single
{
    private static  $instance ;
    private function __construct(){}
    private function __clone(){}
    public static function getInstance() {
        if (empty(self::$instance)) {
            self::$instance = new single();
        }
        return self::$instance;
    }
}
Copy after login

Add a method to the singleton class to get the ID. A globally unique ID number generator appears.

class single
{
    private  $id = 0;
    private static  $instance ;
    private function __construct(){}
    private function __clone(){}
    public static function getInstance() {
        if (empty(self::$instance)) {
            self::$instance = new single();
        }
        return self::$instance;
    }
    public function getId() {
        
        return $this->id++;
        
    }
}
Copy after login

It’s really impeccable, so what happens in the case of multi-threading?

Implementing the only single instance of a thread

I have to mention the difference between ts and nts versions of php, nts (Non Thread Safe) single-thread construction, shared cache data between threads. ts (Thread Safe) is built with multi-threading capabilities and uses different data copies among multiple threads.

Use the ts version of php to automatically upgrade to thread-safe mode. The pthreads extension can only be installed on the ts version of php.

The last version of pthreads included in pecl is based on php7.0. The pthreads project on github has also stopped updating. If you are interested, you can only go to 7.0 to miss the history.

I installed the pthreads extension under the php-7.0.9-Win32-VC14-x64 version.

In the case of multi-threading, the scope of the singleton changes from process-only to thread-only.

require 'single.php';
class Request extends Thread {
    public $url;
    public function __construct($url) {
        $this->url = $url;
    }
    public function run() {
        echo single::getInstance()->getId();
        echo "\n";
    }
}
$chG = new Request("www.google");
$chG ->start();
$chG->join();
echo $chG->getThreadId();
echo "\n";
$chB = new Request("www.baidu");
$chB ->start();
$chB->join();
echo $chB->getThreadId();
echo "\n";
Copy after login

Two threads are created here, but the id starting from 0 can be obtained in both executions, indicating that the single classes in the two threads are two different singleton objects.

Summary

It takes three steps to implement PHP’s singleton mode

* A static Member variables are used to save classes.

* __construct and __clone are declared private to prevent creation or cloning.

* A static method, usually getInstance, used to access this instance.

I have never used multi-threading in PHP. It seems to be a point of no return. I don’t know what everyone thinks.

The above is the detailed content of [Design Pattern] Application scenarios and implementation of PHP singleton pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

One article to understand the singleton pattern in JavaScript One article to understand the singleton pattern in JavaScript Apr 25, 2023 pm 07:53 PM

The JS singleton pattern is a commonly used design pattern that ensures that a class has only one instance. This mode is mainly used to manage global variables to avoid naming conflicts and repeated loading. It can also reduce memory usage and improve code maintainability and scalability.

The application of singleton mode and factory mode in C++ function overloading and rewriting The application of singleton mode and factory mode in C++ function overloading and rewriting Apr 19, 2024 pm 05:06 PM

Singleton pattern: Provide singleton instances with different parameters through function overloading. Factory pattern: Create different types of objects through function rewriting to decouple the creation process from specific product classes.

Getting Started with PHP: Singleton Pattern Getting Started with PHP: Singleton Pattern May 20, 2023 am 08:13 AM

In software development, we often encounter situations where multiple objects need to access the same resource. In order to avoid resource conflicts and improve program efficiency, we can use design patterns. Among them, the singleton pattern is a commonly used way to create objects, which ensures that a class has only one instance and provides global access. This article will introduce how to use PHP to implement the singleton pattern and provide some best practice suggestions. 1. What is the singleton mode? The singleton mode is a commonly used way to create objects. Its characteristic is to ensure that a class has only one instance and provides

Thoughts on thread safety issues in singleton mode in PHP Thoughts on thread safety issues in singleton mode in PHP Oct 15, 2023 am 10:14 AM

Thinking about thread safety issues of singleton mode in PHP In PHP programming, singleton mode is a commonly used design pattern. It can ensure that a class has only one instance and provide a global access point to access this instance. However, when using the singleton pattern in a multi-threaded environment, thread safety issues need to be considered. The most basic implementation of the singleton pattern includes a private constructor, a private static variable, and a public static method. The specific code is as follows: classSingleton{pr

In PHP, what is the concept of singleton design pattern? In PHP, what is the concept of singleton design pattern? Aug 18, 2023 pm 02:25 PM

The Singleton pattern ensures that a class has only one instance and provides a global access point. It ensures that only one object is available and under control in the application. The Singleton pattern provides a way to access its unique object directly without instantiating the object of the class. Example<?php classdatabase{ publicstatic$connection; privatefunc

PHP Design Patterns: The Path to Code Excellence PHP Design Patterns: The Path to Code Excellence Feb 21, 2024 pm 05:30 PM

Introduction PHP design patterns are a set of proven solutions to common challenges in software development. By following these patterns, developers can create elegant, robust, and maintainable code. They help developers follow SOLID principles (single responsibility, open-closed, Liskov replacement, interface isolation and dependency inversion), thereby improving code readability, maintainability and scalability. Types of Design Patterns There are many different design patterns, each with its own unique purpose and advantages. Here are some of the most commonly used PHP design patterns: Singleton pattern: Ensures that a class has only one instance and provides a way to access this instance globally. Factory Pattern: Creates an object without specifying its exact class. It allows developers to conditionally

Extension and customization of singleton pattern in PHP framework Extension and customization of singleton pattern in PHP framework Oct 15, 2023 am 11:10 AM

Extension and customization of singleton mode in PHP framework [Introduction] Singleton mode is a common design pattern, which ensures that a class can only be instantiated once in the entire application. In PHP development, the singleton pattern is widely used, especially in the development and expansion of frameworks. This article will introduce how to extend and customize the singleton pattern in the PHP framework and provide specific code examples. [What is the singleton pattern] The singleton pattern means that a class can only have one object instance and provides a global access point for external use. In PHP development, pass

Application scenarios and thread safety processes of singleton mode in PHP distributed systems Application scenarios and thread safety processes of singleton mode in PHP distributed systems Oct 15, 2023 pm 04:48 PM

Application scenarios and thread safety processes of singleton mode in PHP distributed systems Introduction: With the rapid development of the Internet, distributed systems have become a hot topic in modern software development. In distributed systems, thread safety has always been an important issue. In PHP development, the singleton pattern is a commonly used design pattern, which can effectively solve the problems of resource sharing and thread safety. This article will focus on the application scenarios and thread safety processes of the singleton pattern in PHP distributed systems, and provide specific code examples. 1. Singleton mode

See all articles