jakulov/container

简单的通用容器 & DI容器

dev-master 2016-01-02 20:16 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:20:37 UTC


README

简单的通用PHP容器 & DI容器 (依赖注入)

可以使用composer安装

composer require jakulov/container

实现了 容器互操作性

1. 容器

容器可以用来存储任何数组数据(例如配置或存储库),并使用点符号轻松访问。

$config = ['test' => [
        'key1' => 'value1',
    ]];
$container = \jakulov\Container\Container::getInstance($config);
echo $container->get('test.key1'); // value1

容器和DIContainer使用单例模式,因此容器第一次初始化后,您可以不传递配置作为参数来访问它,例如

// second and other usages of container should not use config
$container = \jakuov\Container\Container::getInstance();

2. DIContainer

依赖注入容器应该用于在PHP应用程序中管理服务之间的依赖关系。这是一个简单但灵活的DI容器实现。

$config = [
    'foo' => 'bar', 
    // you can use aware-interfaces to manage dependencies in app 
    'container' => [
      'di' => [
          'aware' => [
              // in any service class implements this interface and resolved
              // with DIContainer will be called setInterfaceTest method with argument
              // containing instance of service "service.interface_test"
              'Service\\InterfaceTestServiceAwareInterface' => [
                  'setInterfaceTest' => '@service.interface_test',
              ],
          ],
      ],
    ],
    // configuration of services
    'service' => [
      // service name will be "service.test"
      'test' => [
          'class' => 'Service\\TestService', // class of service
          // arguments of service __construct
          'args' => [
              'argument1',
              'argument2'
          ],
          // setters to call while service initialization
          'aware' => [
              // as dependency you can use:
              'setAnotherTestService' => '@service.another_test', // another service
              'setContainerValue' => ':foo', // container value
              'setScalarValue' => 'value', // or scalar value
          ],
      ],
      'another_test' => [
          'class' => 'Service\\AnotherTestService',
      ],
      'alias_test' => '@another_test',
      'interface_test' => [
          'class' => 'Service\\InterfaceTestService'
      ],
    ],
];
  
$dic = \jakulov\Container\DIContainer::getInstance($config);
$testService = $dic->get('service.test');
echo $testService->argument1; // 'argument1'
echo $testService->containerValue; // 'bar'
echo $testService->scalarValue; // 'value'
echo get_class( $testService->anotherTestService ); // Service\\AnotherTestService
echo get_class( $testService->anotherTestService->interfaceTestService ); // Service\\InterfaceTestService

服务也可以通过在类中声明依赖关系接口来解析依赖关系,而无需在配置中声明。

$service = $dic->resolve(\Service\UnresolvedTestService::class);

如果您想使服务在多个请求中可重用,您应该在每次请求中重新设置一些依赖关系。例如,可以是HTTP请求实例。如果请求服务声明为id "request",您可以通过这种方式提供新对象

$request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
$dic->provide('request', $request); // updated dependency in all services

测试

运行:./run_tests.sh

测试也是库使用示例