wok / services
WOK服务提供者和依赖注入
v1.1.1
2017-03-21 15:54 UTC
This package is auto-updated.
Last update: 2024-09-25 06:44:41 UTC
README
这个库是一个轻量级的 依赖注入。
免责声明:该组件是WOK(Web Operational Kit)框架的一部分。然而,它也可以作为一个独立的库使用。
安装
建议使用 Composer 将该组件作为依赖项安装
composer require wok/services
如果没有依赖项,您也可以通过 git 或通过 直接下载 获取。
git clone https://github.com/web-operational-kit/services.git
特性
虽然已经开发了很多依赖注入器(如 pimple/pimple 或 league/container),但这个库的路线图有一些特定的特点
- Services组件是一个依赖注入器(通常)。
- 依赖实例必须在Services对象的生命周期内进行缓存(这就是依赖注入模式)。
- 依赖实例的构造函数可以接受参数,而不会与前述要点有任何麻烦。
让我们在 使用说明 中看看。
使用说明
基本使用
use \WOK\Services\Services; $services = new Services(); // Sample with Doctrine/Cache as `cache` service. $services->addService('cache', function() { return new \Doctrine\Common\Cache\FilesystemCache( './var/cache'); }); // Far far away ... // Retrieve the service $cache = $services->getService('cache');
带有参数
use \WOK\Services\Services; $services = new Services(); // Sample with Symfony/Translation as `translator` service and the locale code as parameter $services->addService('translator', function($locale) { $translator = new \Symfony\Component\Translation\Translator($locale); $translator->addLoader('ini', new \Symfony\Component\Translation\Loader\IniFileLoader()); $files = new DirectoryIterator($path); foreach($files as $resource) { if($resource->getExtension() != 'ini') { continue; } // Only accepted files as `domain.locale.(ini|yml)` $basename = $resource->getBasename(); $domain = mb_substr($basename, 0, mb_strpos($basename, '.')); $translator->addResource($resource->getExtension(), $resource->getPathname(), $locale, $domain); } return $translator; }); // Far far away ... $translator = $services->getService('translator', array('fr_FR'));