stratadox / di
最简单的依赖注入容器
v1.0.2
2018-01-23 02:26 UTC
Requires
- php: >=7.0
- psr/container: ^1.0
Requires (Dev)
- phpunit/phpunit: ^6.5
- satooshi/php-coveralls: ^2.0
This package is auto-updated.
Last update: 2024-09-29 04:36:44 UTC
README
极简依赖注入容器
服务通过匿名函数进行懒加载。
安装
使用composer安装
composer require stratadox/di
基本用法
// Create container $container = new DependencyContainer(); // Set service $container->set('some_service', function () { return new SomeService(); }); // Get service $service = $container->get('some_service'); // Check if service exists $hasService = $container->has('some_service'); // Remove service $container->forget('some_service');
或者,您也可以使用数组语法
// Create container $container = new ArrayAdapter(new DependencyContainer()); // Set service $container['some_service'] = function () { return new SomeService(); }; // Get service $service = $container['some_service']; // Check if service exists $hasService = isset($container['some_service']); // Remove service unset($container['some_service']);
通过装饰容器为AutoWiring对象,可以自动完成大部分配置工作
// Create container $container = AutoWiring::the(new DependencyContainer); $foo = $container->get(Foo::class);
依赖服务
您可以通过在匿名函数中传递DI容器来构建使用其他服务的服务。
$container = new DependencyContainer(); $container->set('collaborator', function () { return new Collaborator(); }); $container->set('main_service', function () use ($container) { return new MainService($container->get('collaborator')); }); $service = $container->get('main_service');
由于服务是懒加载的,所以它们定义的顺序并不重要,只要在请求时全部定义即可。因此,在上面的例子中,我们可以在定义 collaborator
之前定义 main_service
,只要我们不先请求 main_service
。
参数
要向服务传递其他参数,请将它们也传递给您的匿名函数。
$dsn = 'mysql:host=localhost;dbname=testdb'; $username = 'admin'; $password = 'secret'; $container = new DependencyContainer(); $container->set('database', function () use ($dsn, $username, $password) { return new DatabaseConnection($dsn, $username, $password); });
缓存
默认情况下,服务被缓存。您可以通过将缓存设置为false来在每次请求时触发工厂。
// Set service $container->set('some_service', function () { return new SomeService(); }, false);