Design Patterns in PHP 8: Singleton & Multiton

I want talk about design patterns in php in a few next articles. And I really like how language progress that’s why I’ll make examples with last novations of php 8.

Singleton

Sometimes we need only one instance of some class in different co…


This content originally appeared on DEV Community and was authored by Max Zhuk

I want talk about design patterns in php in a few next articles. And I really like how language progress that's why I'll make examples with last novations of php 8.

Singleton

Sometimes we need only one instance of some class in different code places. For example, when we make web application usually it needs connect to database and it will be really good idea to create just one copy of the connection and use it in every files, classes, functions. The pattern that will help us with this - Singleton is one of the most popular and easiest design pattern.

Let's see how we can implement classes database connection and logging with one instance in all objects:

class Singleton
{
    protected static self|null $instance = null;

    final private function __construct(){}
    final protected function __clone(){}
    final protected function __wakeup(){}

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

        return self::$instance;
    }
}

class Database extends Singleton
{
    public function connect()
    {
        // ...
    }
}

class Logger extends Singleton
{
    public static function error(string $message)
    {
        // ...
    }

    public static function warn(string $message)
    {
        // ...
    }
}

How to use it:

$db = Database::getInstance();
$db->connect();

$logger = Logger::getInstance();
$logger::error('Something wrong');

Multiton

But what if we need more then just one instance of logger because some messages must be write in file, some need send by email? Or we can have other reasons. For that we'll use Multiton pattern. Multiton looks really resembling previous pattern but with array of instance of class.

class Multiton
{
    protected static array|null $instance = null;

    final private function __construct(){}
    final protected function __clone(){}
    final protected function __wakeup(){}

    public static function getInstance(int|string $key): self
    {
        if (!array_key_exists($key, self::$instance)) {
            self::$instance[$key] = new self;
        }

        return self::$instance[$key];
    }
}

class Logger extends Multiton
{
    private array $settings;

    public function setSettings(array $settings)
    {
        // ...
    }

    public function error(string $message)
    {
        // ...
    }

    public function warn(string $message)
    {
        // ...
    }
}

Let's make two loggers with different settings for saving logs into files and database. I won't describe setter of settings and writer to file/database in details cause it isn't important for pattern.

$fileLogger = Logger::getInstance('file');
$fileLogger->setSettings([
    //...
]);
$fileLogger->error('Error text');

$dbLogger = Logger::getInstance('database');
$dbLogger->setSettings([
    //...
]);
$dbLogger->error('Error will write in Database');


This content originally appeared on DEV Community and was authored by Max Zhuk


Print Share Comment Cite Upload Translate Updates
APA

Max Zhuk | Sciencx (2022-07-20T23:03:12+00:00) Design Patterns in PHP 8: Singleton & Multiton. Retrieved from https://www.scien.cx/2022/07/20/design-patterns-in-php-8-singleton-multiton/

MLA
" » Design Patterns in PHP 8: Singleton & Multiton." Max Zhuk | Sciencx - Wednesday July 20, 2022, https://www.scien.cx/2022/07/20/design-patterns-in-php-8-singleton-multiton/
HARVARD
Max Zhuk | Sciencx Wednesday July 20, 2022 » Design Patterns in PHP 8: Singleton & Multiton., viewed ,<https://www.scien.cx/2022/07/20/design-patterns-in-php-8-singleton-multiton/>
VANCOUVER
Max Zhuk | Sciencx - » Design Patterns in PHP 8: Singleton & Multiton. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/07/20/design-patterns-in-php-8-singleton-multiton/
CHICAGO
" » Design Patterns in PHP 8: Singleton & Multiton." Max Zhuk | Sciencx - Accessed . https://www.scien.cx/2022/07/20/design-patterns-in-php-8-singleton-multiton/
IEEE
" » Design Patterns in PHP 8: Singleton & Multiton." Max Zhuk | Sciencx [Online]. Available: https://www.scien.cx/2022/07/20/design-patterns-in-php-8-singleton-multiton/. [Accessed: ]
rf:citation
» Design Patterns in PHP 8: Singleton & Multiton | Max Zhuk | Sciencx | https://www.scien.cx/2022/07/20/design-patterns-in-php-8-singleton-multiton/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.