Singleton pattern in PHP

Singleton pattern in PHP

What is the Singleton pattern

The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance.

Why we use it

  1. Single Instance: Ensures that a class has only one instance, which is useful in scenarios where a single point of control or coordination is required.
  2. Global Access: Provides a global point of access to the instance, making it easy to access and manage from anywhere in the codebase.
  3. Lazy Initialization: The instance is created only when it is first needed, improving performance by avoiding unnecessary instantiation.

How Use it

Example :

we'll use a DatabaseConnection class as a Singleton website to manage a single database connection throughout the website

class DatabaseConnection {
    private static $instance;
    private $connection;

    private function __construct() {
        // database connection
        $this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    }

    public static function getInstance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function getConnection() {
        return $this->connection;
    }
}

// Example usage in a web pages: 

$database = DatabaseConnection::getInstance();
$connection = $database->getConnection();

// Now you can use $connection to perform database queries throughout your webpage
// without establishing a new connection every time.        

Another example we can use for session management in website

class AuthManager {
    public static function login($username, $password) {
        // authentication logic, check credentials against a database
        if ($username === 'demo' && $password === 'password') {
            $_SESSION['user'] = $username;
            return true;
        }
        return false;
    }

    public static function logout() {
        // Perform logout logic, destroy the session
        session_destroy();
    }

    public static function isAuthenticated() {
        // Check if a user is authenticated
        return isset($_SESSION['user']);
    }

    public static function getCurrentUser() {
        // Get the current user from the session
        return $_SESSION['user'] ?? null;
    }
}

// Usage example in web pages:

session_start();

// Perform login
AuthManager::login('demo', 'password');

// Check authentication status
if (AuthManager::isAuthenticated()) {
    echo "Welcome, " . AuthManager::getCurrentUser();
} else {
    echo "Not authenticated. Redirect to login page.";
}
        

above example are simple.

要查看或添加评论,请登录

ranush malsika的更多文章

  • Docker Architecture

    Docker Architecture

    Multiple containers from a single image Layers of image How Docker Swarm manages containers, services, and stacks…

  • I think a relevant book for every developer the Designing Data-Intensive Applications book

    I think a relevant book for every developer the Designing Data-Intensive Applications book

    This book is a comprehensive guide to designing large-scale distributed systems. Here's a concise overview of the main…

  • I think a relevant book for front-end designers the Refactoring UI book

    I think a relevant book for front-end designers the Refactoring UI book

    It's particularly useful for developers, startup founders, and anyone who needs to create interfaces but doesn't have…

  • How JWT Works in a Website (Simply idea)

    How JWT Works in a Website (Simply idea)

    JWT stands for JSON Web Token. It's a compact and self-contained way for securely transmitting information between…

  • nextTick function in vue js

    nextTick function in vue js

    nextTick is often used after the DOM has been updated to ensure that any changes made to the DOM are fully reflected…

  • What is async ?

    What is async ?

    async is a keyword used in programming, particularly in languages like JavaScript, Python, and C#, that allows…

  • onDeactivated in vue js

    onDeactivated in vue js

    to handle when a component is deactivated, meaning it is cached and removed from the DOM without being destroyed.

  • onActivated in vue js

    onActivated in vue js

    =Home onActivated hook in Vue.js is used in the context of components to handle when a component is activated.

  • onRenderTriggered in vue js

    onRenderTriggered in vue js

    =Home onRenderTriggered hook in Vue.js is used to monitor when a reactive dependency has been triggered during the…

  • onRenderTracked in vue js

    onRenderTracked in vue js

    =Home onRenderTracked lifecycle hook in Vue.js is used to monitor reactive dependencies that are being tracked during…

社区洞察

其他会员也浏览了