pokmot/pimple-singleton

扩展Pimple以成为单例

3.0.0 2015-09-16 08:11 UTC

This package is auto-updated.

Last update: 2024-09-24 05:24:45 UTC


README

任务很简单:我想在代码的任何地方轻松获取我的Pimple容器。

无论是模块、外部类,还是一个不知道我特定项目使用哪个框架的独立库,或者,我不想担心如何传递它。

所以单例似乎是一个简单选项。

当容器被调用时,会自动创建单例。你可以这样做

new \PimpleSingleton\Container();
$di = \PimpleSingleton\Container::getContainer(); 

你是否已经定义了你的Pimple实例,例如通过框架初始化,或者可能在单元测试中?

$di = new Pimple\Container();
\PimpleSingleton\Container::setContainer($di);
$di = \PimpleSingleton\Container::getContainer();

使用PhpStorm(所有IDE中最伟大的... ;-)

namespace PHPSTORM_META {
  /** @noinspection PhpUnusedLocalVariableInspection */
  /** @noinspection PhpIllegalArrayKeyTypeInspection */
  $STATIC_METHOD_TYPES = [
      \PimpleSingleton\Container::get('') => array(
          'db' instanceof \Aura\Sql\ExtendedPdo,
          'request' instanceof \Slim\Http\Request,
          'response' instanceof \Slim\Http\Response
      )
  ];
}

现在PhpStorm将为类似这样的代码执行自动补全

$db = \PimpleSingleton\Container::get('db');

享受吧!