sitepoint / container
一个简单、易于理解的PHP依赖注入容器
v0.1.0
2015-10-24 20:48 UTC
Requires
Requires (Dev)
- satooshi/php-coveralls: dev-master
This package is not auto-updated.
Last update: 2024-09-14 18:35:37 UTC
README
一个简单、易于理解的PHP依赖注入容器。设计用于分支、修改、扩展和修改。
如何使用
虽然这样做不是必需的,但将容器配置拆分是良好的实践。在这个例子中,我们将使用三个文件来创建用于Monolog组件的容器。
另一个好的实践是使用类和接口路径作为服务名称。这提供了一个更严格的命名约定,使我们能够获取更多关于服务的信息。
在服务定义文件中,我们定义了三个服务。所有服务都需要构造函数注入参数。其中一些参数是从容器参数导入的,而另一些则是直接定义的。日志服务还需要对pushHandler
方法进行两次调用,每次都导入不同的处理程序服务。
<?php // config/services.php // Value objects are used to reference parameters and services in the container use SitePoint\Container\Reference\ParameterReference as PR; use SitePoint\Container\Reference\ServiceReference as SR; use Monolog\Logger; use Monolog\Handler\NativeMailerHandler; use Monolog\Handler\StreamHandler; use Psr\Log\LoggerInterface; return [ StreamHandler::class => [ 'class' => StreamHandler::class, 'arguments' => [ new PR('logger.file'), Logger::DEBUG, ], ], NativeMailHandler::class => [ 'class' => NativeMailerHandler::class, 'arguments' => [ new PR('logger.mail.to_address'), new PR('logger.mail.subject'), new PR('logger.mail.from_address'), Logger::ERROR, ], ], LoggerInterface::class => [ 'class' => Logger::class, 'arguments' => [ 'channel-name' ], 'calls' => [ [ 'method' => 'pushHandler', 'arguments' => [ new SR(StreamHandler::class), ] ], [ 'method' => 'pushHandler', 'arguments' => [ new SR(NativeMailHandler::class), ] ] ] ] ];
参数定义文件仅返回一个值数组。这些定义为N维数组,但它们通过引用使用以下符号访问:'logger.file'
或'logger.mail.to_address'
。
<?php // config/parameters.php return [ 'logger' => [ 'file' => __DIR__.'/../app.log', 'mail' => [ 'to_address' => 'webmaster@domain.com', 'from_address' => 'alerts@domain.com', 'subject' => 'App Logs', ], ], ];
容器文件仅提取服务和参数定义,并将它们传递给Container
类构造函数。
<?php // config/container.php use SitePoint\Container\Container; $services = include __DIR__.'/services.php'; $parameters = include __DIR__.'/parameters.php'; return new Container($services, $parameters);
现在我们可以在我们的应用程序中获取容器并使用日志服务。
<?php // app/file.php use Psr\Log\LoggerInterface; require_once __DIR__.'/../vendor/autoload.php'; $container = include __DIR__.'/../config/container.php'; $logger = $container->get(LoggerInterface::class); $logger->debug('This will be logged to the file'); $logger->error('This will be logged to the file and the email');
作者
变更日志
此项目维护一个变更日志文件
许可证
MIT许可证(MIT)。请参阅LICENSE获取更多信息。