hermes-php / container
1.0.0
2018-12-21 23:18 UTC
Requires
- php: >=7.2
- psr/container: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.12
- phpunit/phpunit: ^7.3
This package is auto-updated.
Last update: 2019-08-18 18:27:29 UTC
README
简单的PSR-11依赖注入容器
安装
$ composer require hermes-php/container
使用
Hermes容器是一个非常简单和最小的容器。它特别适合不需要真正复杂功能的情况。它涵盖了大多数依赖注入容器的用例。
创建容器的最简单方法是通过传递一个服务数组
<?php
use MyAwesomeApp\Services;
use MyAwesomeApp\Factories;
use Psr\Container\ContainerInterface;
$services = [
// You can pass any kind of callable, like invokable service factories
Services\ServiceOne::class => new Factories\ServiceOneFactory(),
// You can pass an anonymous functions directly too
Services\ServiceTwo::class => function(ContainerInterface $container) {
return new Services\ServiceTwo();
},
// When you don't need complex instantiation logic, you can register a simple class name
// Hermes Container will try to autowire it based on its constructor dependencies.
Services\ServiceThreeInterface::class => Services\ServiceThreeConcrete::class
];
// Then, you pass all this to the Hermes Container constructor
$container = new \Hermes\Container\HermesContainer($services);
// Then you can fetch its dependencies by the service name.
$container->get(Services\ServiceThreeInterface::class);
容器构建器
对于简单的数组配置不足以满足需求的情况,你可以使用容器构建器。这是一个服务,它允许你使用更多的配置和控制来注册服务。
你甚至可以将这个构建器“传递”给你的应用程序中的插件或模块,以便它们可以在此容器中注册它们的服务。
<?php
use Hermes\Container\Builder\ContainerBuilder;
use MyAwesomeApp\Services;
use MyAwesomeApp\Factories;
use Hermes\Container\Builder\Reference;
use Hermes\Container\HermesContainer;
$builder = new ContainerBuilder();
// Lets start with a factory
$builder->factory(Services\ServiceOne::class, new Factories\ServiceOneFactory())
// This will give you a different instance every time the service is fetched
->noSingleton();
// And now a class.
$builder->class(Services\ServiceThreeInterface::class, Services\ServiceThreeConcrete::class)
// We want to auto wire it's constructor dependencies
->autowire()
// And we want to call another setter method with a reference to another service.
->addMethodCall('setLogger', new Reference(\Psr\Log\LoggerInterface::class))
// You can also make this a non-singleton
->noSingleton()
// If you don't like autowiring (because reflection is expensive), you can be
// explicit about the constructor arguments.
->setConstructorArguments(new Reference(Services\SomeService::class), new Reference(Services\AnotherService::class));
// Finally, you can create an alias for a service
$builder->alias(Services\ServiceThreeInterface::class, 'serviceThree');
// When you are done, you can build the Container from the Builder instance.
$container = HermesContainer::fromBuilder($builder);
这就是全部内容了!