phapi/di

此包已被废弃,不再维护。未建议替代包。

Phapi 依赖注入容器

1.0.0 2015-07-02 08:18 UTC

This package is not auto-updated.

Last update: 2021-02-05 21:36:37 UTC


README

Build status Code Climate Test Coverage

Phapi 内置了依赖注入容器,可用于存储对象和参数。它易于使用,并且由于 Phapi 使用容器来存储其大部分对象、依赖和参数,因此有机会替换许多内置功能。

可以通过使用 $this->container 参数在端点中访问容器。

安装

Phapi 框架默认安装了此包。若要单独使用,可以使用 composer 安装。

$ composer require phapi/di:1.*

定义参数

最简单的例子是将参数存储在容器中

<?php
// Set parameter
$container['param'] = 'value';

// Get parameter
echo $container['param']; // Output: value

定义对象和依赖

通过返回对象实例的匿名函数定义对象及其依赖。您有两种方法可以定义它们。一种是使用

<?php
// Define database configuration
$container['dbUserName'] = 'root';
$container['dbPassword'] = '1234';

// Add DB connection to container
$container['dbConn'] = function ($container) {
  return new PDO(
    'mysql:host=localhost;dbname=test',
    $container['dbUserName'],
    $container['dbPassword']
  );
};

或者使用 bind() 方法

<?php
// Define database configuration
$container['dbUserName'] = 'root';
$container['dbPassword'] = '1234';

// Add DB connection to container
$container->bind('dbConn', function ($container) {
  return new PDO(
    'mysql:host=localhost;dbname=test',
    $container['dbUserName'],
    $container['dbPassword']
  );
});

请注意,函数可以访问容器实例,这使得从容器中检索参数和依赖成为可能。

默认情况下,容器会在每次获取时返回相同实例的对象。bind() 方法接受一个可选的第三个参数来定义在创建对象时是否应使用 单例多例 模式。默认是单例。将其更改为多例,每次调用 $container['dbConn'] 时将创建并返回一个新的实例。示例

<?php
// Define database configuration
$container['dbUserName'] = 'root';
$container['dbPassword'] = '1234';

// Add DB connection to container
$container->bind('dbConn', function ($container) {
  return new PDO(
    'mysql:host=localhost;dbname=test',
    $container['dbUserName'],
    $container['dbPassword']
  );
}, \Phapi::TYPE_MULTITON);

由于对象是在获取时创建的,因此定义的顺序无关紧要。

检索对象和/或参数

使用对象很简单

<?php
// Use DB connection
$container['dbConn']->query('SELECT ...');

或者使用 make() 方法

<?php
// Get DB connection
$db = $container->make('dbConn');
// Use the connection
$db->query('Select ...');

移除对象和/或参数

容器实现了 \ArrayAccess 接口,这使得它可以用作常规数组。移除对象或参数只需取消设置它即可

<?php
unset($container['dbConn']);

验证器

在某些情况下,您可能想确保某个键具有特定类型的值。Phapi 需要 $container['log'] 是 PSR-3 兼容的日志记录器。为了强制执行此操作,将验证器分配给 log 键。

<?php
// Register validator
$container->addValidator('log', new \Phapi\Container\Validator\Log($this));

验证器的 validate() 方法是检查提供的日志记录器是否兼容 PSR-3 的简单检查

<?php
/**
 * Validates the configured logger. If no logger is configured or
 * if the configured logger isn't PSR-3 compliant an instance of
 * NullLogger will be used instead.
 *
 * The PSR-3 package includes a NullLogger that doesn't do
 * anything with the input but it also prevents the application
 * from failing.
 *
 * This simplifies the development since we don't have to check
 * if there actually are a valid cache to use. We can just ask
 * the Cache (even if its a NullCache) and we will get a response.
 */
public function validate($logger)
{
    $original = $logger;

    if (is_callable($logger)) {
        $logger = $logger($this->container);
    }

    // Check if logger is an instance of the PSR-3 logger interface
    if ($logger instanceof LoggerInterface) {
        return $original;
    }

    // A PSR-3 compatible log writer hasn't been configured so we
    // don't know if it is compatible with Phapi. Therefore we
    // create an instance of the NullLogger instead
    return function ($container) {
        return new NullLogger();
    };
}

如示例所示,即使提供的日志记录器无效,也不会引发错误。这样做是因为我们不希望应用程序因日志记录器错误而崩溃。在其他情况下,抛出异常可能更合适。

许可证

Phapi Di Container遵循MIT许可证 - 有关详细信息,请参阅license.md文件。

贡献

贡献、错误修复等总是受欢迎的。请点击此处提交