bomoko/lethabadi

简单的DI容器实现

0.0.0 2017-09-22 14:56 UTC

This package is auto-updated.

Last update: 2024-09-24 18:35:55 UTC


README

这是一个简单的DI容器,灵感来自(或者说,毫不客气地复制自)Pimple 1.x

用法

实例化容器

$container = new DIContainer();

您可以在构造时可选地传递一个初始参数数组

$container = new DIContainer(['parameter' => 'value']);

检索参数和服务

从容器中提取参数和服务的有两种选择

$output = $container('serviceName');

$output = $container->get('serviceName'); //PSR-11风格

定义参数和服务

您可以通过将它们绑定到容器来添加简单的值、对象和函数

$container->bind('serviceName' => $service);

然后,您可以通过调用容器的服务名称来访问该服务

$serviceResult = $container('serviceName');

保护参数

如果您想将可调用的对象作为参数存储,您必须使用protect()方法将其绑定到容器。默认情况下,容器将尝试在服务解析期间运行任何可调用的对象。保护参数意味着您可以保证得到您放入的内容。

$container->protect('protectedParameter', function () { return 'will run outside container';});

定义共享服务

共享服务每次解析服务时都返回相同的实例。要定义共享服务,只需使用bindSingleton方法将其绑定到容器。

$container->bindSingleton('serviceName', function ($c) {
   return new someSharedObject($c('someParameter')); 
});

修改现有服务

您可以通过使用extend()方法来修改现有服务的行为。服务扩展应该可以接受两个参数,第一个是现有服务返回的值,第二个是容器实例。

以下是一个定义返回字符串的服务,然后扩展它以修改字符串的示例。

$container = new DIContainer();
$container->bind('service', function ($c) {
    return "inside";
});

$container->extend('service', function ($innerResult, $c) {
  return "outside-" . $innerResult . "-outside";
});

$output = $container('service'); //will contain 'outside-inside-outside'