hafo / di
Hafo 框架依赖注入
Requires
- php: >=7.1.0
- psr/container: 1.0.0
Requires (Dev)
- phpunit/phpunit: ^7.5
Suggests
- nette/caching: To be able to use NetteCache class for Autowiring
README
这是什么?
这是一个小型 PHP 依赖注入容器,具有自动装配和尽可能少的配置。它扩展了 Psr\Container\ContainerInterface
并提供了一些帮助加速开发的特性。
如何安装此软件包?
通过 Composer
composer require hafo/di
需要 PHP 版本 7.1 或更高。
如何使用?
最简单的方法是使用 ContainerBuilder
类
use Hafo\DI\ContainerBuilder; $builder = new ContainerBuilder(); // configure the builder $builder->addFactories([ Symfony\Component\Console\Application::class => function () { return new Symfony\Component\Console\Application(); } ]); $container = $builder->createContainer(); // run the application $application = $container->get(Symfony\Component\Console\Application::class); $application->run();
添加服务工厂
您可以通过 ContainerBuilder 添加服务
$builder->addFactories([ Symfony\Component\Console\Application::class => function () { return new Symfony\Component\Console\Application(); }, // ... add more services ]);
建议使用类名作为标识符,因为这些可以被用于自动装配,如果启用的话。这也是最佳实践。
参数可以是数组,或任何可迭代的,只要它提供键和工厂回调。
装饰服务
装饰器是一个简单的回调,在创建服务时会被调用。它可以用来在返回服务之前修改服务。
use Hafo\DI\Container; $builder->addDecorators([ Symfony\Component\Console\Application::class => [ function (Symfony\Component\Console\Application $application, Container $container) { $application->add($container->get(MyProject\Console\SomeCommand::class)); }, // ... add more decorators for Application class ], // ... add more decorators for other services ]);
是否为服务使用装饰器的决策是通过简单的 is_a()
检查完成的,因此您可以轻松地为实现相同接口的多个服务进行装饰,例如。
容器确保每个装饰器只为每个服务实例调用一次。
添加参数
您还可以添加参数
$builder->addParameters([ 'rootDir' => __DIR__, // ... add more parameters ]);
然后参数将被注册到 DI 容器中,并且可以通过 get()
方法访问,就像服务一样。
使用自动装配
如果您想避免手动编写许多工厂,可以使用自动装配。只需确保您的服务构造函数参数是可以解析的,这意味着所有依赖项都必须可以使用 DI 容器实例化,或者它们必须具有默认值。
use Hafo\DI\Autowiring\AutowiringCache\MemoryCache; use Hafo\DI\Autowiring\DefaultAutowiring; use Hafo\DI\ContainerBuilder; $builder = new ContainerBuilder(); $builder->setAutowiring(new DefaultAutowiring(new MemoryCache())); $container = $builder->createContainer();
如果您使用 nette/caching
软件包,可以使用 Hafo\DI\Autowiring\AutowiringCache\NetteCache
代替 MemoryCache
。
您还可以实现自己的 Hafo\DI\Autowiring\AutowiringCache
或甚至 Hafo\DI\Autowiring
。
接口-实现映射
对于您的服务使用接口是一种好习惯。然而,DI 容器默认不知道您想要返回哪个特定类。我们需要指定它
$builder->addInterfaceImplementationMap([ Doctrine\ORM\EntityManagerInterface::class => Doctrine\ORM\EntityManager::class ]);
可重用模块
您可以通过实现 Hafo\DI\Module
接口来创建简单的可重用模块。然后,在您的项目中使模块工作就像实例化它并调用方法 install
,传递构建器作为参数一样简单。