定制 oliver-schoendorn/dependency-injector 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

oliver-schoendorn/dependency-injector

Composer 安装命令:

composer require oliver-schoendorn/dependency-injector

包简介

A very simple dependency injector that supports instance creation and auto wiring of classes, class methods and functions. Additionally it provides simple means of caching the necessary reflections to boost performance in heavy load environments.

README 文档

README

Build Status Coverage Status

Installation

composer require oliver-schoendorn/dependency-injector

Don't forget to include the composer autoloader in your application bootstrap process.

require_once __DIR__  . "/vendor/autoload.php";

Basic Usage

I recommend creating a single instance of the dependency injector during your applications bootstrap or request dispatching process.

The most common use case is to use the dependency injector to create instances of your controllers. In the following example, the dependency injector is used to create an instance of FakeController and to invoke the get method of it. All method parameters will be autowired.

<?php

/**
 * Class FakeController
 * This is a mock controller to show case the most common dependency injection use case
 */
class FakeController
{
    /**
     * @var FakeEntityRepository 
     */
    private $entityRepository;
    
    public function __construct(FakeEntityRepository $entityRepository)
    {
        $this->entityRepository = $entityRepository;
    }
    
    public function get(int $entityId)
    {
        $entity = $this->entityRepository->findById($entityId);
        return $entity->toJSON();
    }
}


// Somewhere in your bootstrap or dispatching process 
use OS\DependencyInjector\DependencyInjector;
use OS\DependencyInjector\ReflectionHandler;

$reflectionHandler = new ReflectionHandler();
$dependencyInjector = new DependencyInjector($reflectionHandler);

// This is just a mock and will likely be generated by your application / framework
$fakeRequestPayload = [ 'entityId' => 123 ];
$fakeRouteHandler   = [ FakeController::class, 'get' ];

function dispatchRequest(
    string $routeControllerClassId,
    string $routeControllerMethod,
    array $requestPayload
) use ($dependencyInjector) {
    // The dependency injector (DI) will create an instance of the given controller class id
    // In this specific example, the DI will attempt to autoload the FakeEntityRepository and inject it into the
    // controller constructor. 
    $controllerInstance = $dependencyInjector->resolve($routeControllerClassId);
    
    // After creating the controller instance, the $routeControllerMethod on the $controllerInstance will be called.
    // The DI will apply the necessary parameters, as long as they are present in the $requestPayload array or if it
    // can be autowired (for example if the get method requires an additional Repository instance for a related entity). 
    return $dependencyInjector->invoke([ $controllerInstance, $routeControllerMethod ], $requestPayload);
}

echo dispatchRequest($fakeRouteHandler[0], $fakeRouteHandler[1], $fakeRequestPayload);

Dealing with shared instances

Some dependencies should only have a single instance (or as few as possible), like a database connection for instance.

<?php

use OS\DependencyInjector\DependencyInjector;
use OS\DependencyInjector\ReflectionHandler;

interface DatabaseConnection { /* ... */ }
class PdoDatabaseConnection implements DatabaseConnection
{
    public function __construct(string $dsn, string $username, string $password, array $options = []) { /* ... */ }
    /* ... */
}

$di = new DependencyInjector(new ReflectionHandler());

// This line will tell the DI to substitute requests to
// DatabaseConnection::class with instances of PdoDatabaseConnection::class
$di->alias(DatabaseConnection::class, PdoDatabaseConnection::class);

// Next we will create an instance of the PdoDatabaseConnection::class
$di->share(new PdoDatabaseConnection('mysql:...', 'username', 'password', []));


// Now, when every the DI is asked for an instance of DatabaseConnection::class or PdoDatabaseConnection::class, it
// will return the same instance as defined above
$pdoDatabaseConnection = $di->resolve(DatabaseConnection::class);

Handling multiple connections (simple)

Sometimes you have to deal with multiple database connections for example. The following example shows how to deal with multiple shared instances of the same class or interface.

Note however, that this approach will not work with auto wiring and also break the type hinting in PhpStorm.

<?php

use OS\DependencyInjector\DependencyInjector;
use OS\DependencyInjector\ReflectionHandler;

$di = new DependencyInjector(new ReflectionHandler());

// Prepare the two different database connection wrappers
$di->share(new PdoDatabaseConnection('mysql:...', 'username1', 'password1', []), 'mysql_read');
$di->share(new PdoDatabaseConnection('mysql:...', 'username2', 'password2', []), 'mysql_write');


// Getting the different connection wrappers
$readConnection = $di->resolve('mysql_read');
$writeConnection = $di->resolve('mysql_write');

Handling multiple connections (verbose)

To circumvent the issues of the previous approach, you could define two additional interface that will be substituted by the read or write connection:

<?php

use OS\DependencyInjector\DependencyInjector;
use OS\DependencyInjector\ReflectionHandler;

$di = new DependencyInjector(new ReflectionHandler());

interface DatabaseReadConnection extends DatabaseConnection {}
interface DatabaseWriteConnection extends DatabaseConnection {}

// Prepare the two different database connection wrappers
$di->share(new PdoDatabaseConnection('mysql:...', 'username1', 'password1', []), DatabaseReadConnection::class);
$di->share(new PdoDatabaseConnection('mysql:...', 'username2', 'password2', []), DatabaseWriteConnection::class);


// Getting the different connection wrappers
$readConnection  = $di->resolve(DatabaseReadConnection::class);
$writeConnection = $di->invoke(function (DatabaseWriteConnection $connection) {
    /* ... */
});

Building complex instance

Approach 1: Predefine constructor arguments

<?php

use OS\DependencyInjector\DependencyInjector;
use OS\DependencyInjector\ReflectionHandler;

$di = new DependencyInjector(new ReflectionHandler());

class ComplexClass
{
    public function __constructor(array $config, string $foo) { /* ... */ }
} 

$di->configure(ComplexClass::class, [ 'config' => [ 'fancy' => 'variables' ] ]);

Old

<?php

use OS\DependencyInjector\DependencyInjector;
use OS\DependencyInjector\ReflectionHandler;
use OS\DependencyInjector\Test\_support\Helper\TestClass01;

$reflectionHandler = new ReflectionHandler();
$dependencyInjector = new DependencyInjector($reflectionHandler);

// Basic class resolving (+ passing an argument)
$instance = $dependencyInjector->resolve(TestClass01::class, [ 'optional' => 'some value']);
assert($instance->constructorArgument === 'some value');

// Resolve dependencies
class SomeClassWithDependencies
{
    public $someOtherClass;
    public function __construct(SomeOtherClass $someOtherClass) {
        $this->someOtherClass = $someOtherClass;
    }
}

class SomeOtherClass
{
    
}

$instance = $dependencyInjector->resolve(SomeClassWithDependencies::class);
assert($instance->someOtherClass instanceof SomeOtherClass);

// Alias
$dependencyInjector->alias(SomeOtherClass::class, SomeClassWithDependencies::class);
$instance = $dependencyInjector->resolve(SomeClassWithDependencies::class);
assert($instance instanceof SomeOtherClass);

// Configure
class YetAnotherClass extends SomeOtherClass
{
    
}

$dependencyInjector->configure(SomeClassWithDependencies::class, [ ':someOtherClass' => YetAnotherClass::class ]);
$instance = $dependencyInjector->resolve(SomeClassWithDependencies::class);
assert($instance->someOtherClass instanceof YetAnotherClass);

// Delegate
class ClassWithSetters
{
    public $logger;
    public function setLogger(Psr\Log\LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
}

// -> the parameters of the delegate method will get resolved by the dependency injector
$delegate = function(Monolog\Logger $logger): SomeClassWithDependencies
{
    $instance = new ClassWithSetters();
    $instance->setLogger($logger);
    return $instance;
};

$dependencyInjector->delegate(ClassWithSetters::class, $delegate);
$instance = $dependencyInjector->resolve(ClassWithSetters::class);
assert($instance->logger instanceof Monolog\Logger);

oliver-schoendorn/dependency-injector 适用场景与选型建议

oliver-schoendorn/dependency-injector 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 105 次下载、GitHub Stars 达 1, 最近一次更新时间为 2017 年 08 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「dependency injection」 「dependency injector」 「auto wiring」 「cached reflections」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 oliver-schoendorn/dependency-injector 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 oliver-schoendorn/dependency-injector 我们能提供哪些服务?
定制开发 / 二次开发

基于 oliver-schoendorn/dependency-injector 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 105
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 4
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2017-08-24