webimpress / zend-pimple-config
1.0.0alpha1
2018-02-07 16:07 UTC
Requires
- php: ^7.1
- pimple/pimple: ^3.2.2
Requires (Dev)
- phpunit/phpunit: ^6.5.4
- zendframework/zend-coding-standard: ~1.0.0
This package is auto-updated.
Last update: 2019-05-01 21:43:19 UTC
README
此库提供了一些工具,用于使用 zend-servicemanager 配置来配置一个兼容 PSR-11 的 Pimple 容器,以便在 Expressive 中使用。
安装
运行以下命令安装此库
$ composer require zendframework/zend-pimple-config
配置
要获取一个配置好的 PSR-11 Pimple 容器,请执行以下操作
<?php use Zend\Pimple\Config\Config; use Zend\Pimple\Config\ContainerFactory; $factory = new ContainerFactory(); $container = $factory( new Config([ 'dependencies' => [ 'services' => [], 'invokables' => [], 'factories' => [], 'aliases' => [], 'delegators' => [], 'extensions' => [], ], // ... other configuration ]) );
dependencies
子关联数组可以包含以下键
services
:一个关联数组,将一个键映射到特定的服务实例。invokables
:一个关联数组,将一个键映射到无构造函数的服务;即对于不需要构造函数参数的服务。键和服务名称可以相同;如果不相同,则名称被视为别名。factories
:一个关联数组,将服务名称映射到工厂类名称,或任何可调用对象。工厂类必须可以无参数实例化,并且一旦实例化就可以调用(即实现__invoke()
方法)。aliases
:一个关联数组,将别名映射到服务名称(或另一个别名)。delegators
:一个关联数组,将服务名称映射到委托工厂键的列表,有关更多详细信息,请参阅 Expressive 委托者文档。extensions
:一个关联数组,将服务名称映射到扩展工厂名称的列表,请参阅下文。
请注意,整个配置都可在
config
键的$container
中找到。$config = $container->get('config');
extensions
extensions
配置仅在 Pimple 容器中可用。如果您正在使用 Aura.Di 或 zend-servicemanager,则可以使用delegators
。如果您希望保持最高的兼容性并考虑将来更改所使用的容器库,则建议使用delegators
。
扩展工厂有以下签名
use Psr\Container\ContainerInterface; public function __invoke( $service, ContainerInterface $container, $name );
传递给扩展工厂的参数如下
$service
是实际的服务实例。$container
是用于为请求的服务创建扩展时使用的容器。$name
是请求的服务名称。
以下是一个扩展工厂的示例
use Psr\Container\ContainerInterface; class ExtensionFactory { public function __invoke($service, ContainerInterface $container, $name) { // do something with $service return $service; } }
您还可以从扩展工厂返回不同的实例
use Psr\Container\ContainerInterface; class ExtensionFactory { public function __invoke($service, ContainerInterface $container, $name) { return new Decorator($service); } }
请注意,在配置扩展时,您必须为服务提供一个 列表 的扩展工厂,而不是单个扩展工厂名称
new Config([ 'dependencies' => [ 'invokables' => [ 'my-service' => MyInvokable\Service::class, ], 'extensions' => [ 'my-service' => [ Extension1Factory::class, Extension2Factory::class, // ... ], ], ], ]);
服务扩展的调用顺序与列表中定义的顺序相同。
与Expressive一起使用
将config/container.php
的内容替换为以下内容
<?php use Zend\Pimple\Config\Config; use Zend\Pimple\Config\ContainerFactory; $config = require __DIR__ . '/config.php'; $factory = new ContainerFactory(); return $factory(new Config($config));