承接 petrknap/singleton 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

petrknap/singleton

最新稳定版本:v2.0.2

Composer 安装命令:

composer require petrknap/singleton

包简介

Singleton pattern for PHP

README 文档

README

Simple implementation of singleton (anti-)pattern.

Why use a singleton?

Because it can solve deadlocks and other problems. See this example:

class UnsafeFileAppender
{
    const MY_FILE = '/tmp/my.file';

    private $handle = null;

    public function __construct()
    {
        $this->handle = fopen(self::MY_FILE, 'a');
        flock($this->handle, LOCK_EX);
    }

    public function __destruct()
    {
        flock($this->handle, LOCK_UN);
        fclose($this->handle);
    }
}

You cannot create two instances at the same time with this code...

$first = new UnsafeFileAppender();  // OK
$second = new UnsafeFileAppender(); // Deadlock

...so simply convert it into singleton...

use PetrKnap\Singleton\SingletonInterface;
use PetrKnap\Singleton\SingletonTrait;

class SafeFileAppender extends UnsafeFileAppender implements SingletonInterface
{
    use SingletonTrait;

    private function __construct()
    {
        parent::__construct();
    }
}

...and use the same instance twice.

$first = SafeFileAppender::getInstance();  // OK
$second = SafeFileAppender::getInstance(); // OK

Run composer require petrknap/singleton to install it. You can support this project via donation. The project is licensed under the terms of the LGPL-3.0-or-later.

统计信息

  • 总下载量: 18.67k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 4
  • Watchers: 1
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: LGPL-3.0-or-later
  • 更新时间: 2024-03-12