定制 mbretter/stk-di 二次开发

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

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

mbretter/stk-di

Composer 安装命令:

composer require mbretter/stk-di

包简介

Dependency injection made easy

README 文档

README

License PHP 8 Latest Stable Version Total Downloads CI

A simple dependency injection system usable with any container implementing the Psr\Container\ContainerInterface.

The service factory supports constructor injection and argument injection for services implementing the Injectable interface.

As a special feature OnDemand services are supported, they support service creation at runtime not at creation time, this avoids a dependency loading bloat for each request, due to complex dependencies. As a side effect OnDemand services may be used to inject objects which are not implementing the Injectable interface, like 3rd party services.

The library comes up with a dumb container implementation, this container is mainly used for testing and demonstration purposes.

Injectable

The injectable interface is a dummy/empty interface for targeting injectable services. Services should implement this interface.

use Stk\Service\Injectable;

class MyService implements Injectable
{
...
} 

Registering services

As a first step you have to put all your services into the container and it is recommended to put the service factory into the container too.

use Stk\Service\DumbContainer;
use Stk\Service\Factory;

class ServiceA implements Injectable
{

}

$container = new DumbContainer();
$container['config'] = [
    'param1' => 'foo',
    'param2' => 'bar'
];

$container['factory']  = new Factory($container); // put the service factory into the container
$container['serviceA'] = function (ContainerInterface $c) {
    return $c['factory']->get(ServiceA::class);
};

Argument injection

The service factory scans each service for private methods having injectables as argument and injects the service by fetching it from the container, using the argument name as key.

class ServiceA implements Injectable
{

}

class ServiceB implements Injectable
{
    protected $serviceA;

    // tell the factory to inject serviceA
    private function setServiceA(Injectable $serviceA)
    {
        $this->serviceA = $serviceA;
    }
}

$container['serviceA'] = function (ContainerInterface $c) {
    return $c['factory']->get(ServiceA::class);
};

$container['serviceB'] = function (ContainerInterface $c) {
    return $c['factory']->get(ServiceB::class);
};

$service = $this->container->get('serviceB');

Constructor injection

When instantiating services, the factory scans the constructor for argument names, if they are found in the container, the service is injected, default values are supported (if the container has no service with the given name). It is not needed, that the injected service implements the injectable interface, any container value may be injected.

class ServiceC implements Injectable
{
    protected $service;
    protected $whatever;

    public function __construct($serviceA, $whatever = [])
    {
        $this->service  = $serviceA;
        $this->whatever = $whatever;
    }
}

Constructor injection with params

If it is needed to pass some kind of static parameters (e.g. config settings) at declaration time and some additional parameters at instantiation time, the service factory skips the passed parameters and only injects the remaining arguments.

class ServiceK implements Injectable
{
    protected $config;
    public $param1;

    // $config should be passed at service declaration, $param1 at creation time
    public function __construct($config, $param1)
    {
        $this->config = $config;
        $this->param1 = $param1;
    }
}

// the container declaration for ServiceK, wrapped inside a Closure
$container['serviceK'] = function ($c) {
    return function ($param2) use ($c) {
        return $c['factory']->get(ServiceK::class, $c->get('config'), $param2);
    };
};

// accessing the service
/** @var Closure $serviceK */
$factory  = $container->get('serviceK');

/** @var ServiceK $serviceK */
$serviceK = $factory('val2');

$serviceK->param1 === 'val2';

OnDemand services

OnDemand services are wrappers around services to avoid the immediate instantiation of dependend services. In bigger projects with tons of services, it is very likely to run into a dependency bloat, ServiceA depends on ServiceB, ServiceB needs ServiceC ... at the end you have all your services instantiated, regardeless whether they are used or not.

class ServiceH implements Injectable
{
    public $arg1 = null;
    public $arg2 = null;

    public function __construct($arg1 = null, $arg2 = null)
    {
        $this->arg1 = $arg1;
        $this->arg2 = $arg2;
    }
}

class ServiceE implements Injectable
{
    /** @var OnDemand */
    public $onDemand;

    // trigger DI of OnDemand service H
    private function setService(OnDemand $serviceH)
    {
        $this->onDemand = $serviceH;
    }

    public function getService()
    {
        return $this->onDemand->getInstance();
    }

    public function newService()
    {
        return $this->onDemand->newInstance();
    }
}

$container['serviceE'] = function ($c) {
    return $c['factory']->get(ServiceE::class);
};
$container['onDemandServiceH'] = function ($c) {
    // the protect method wraps the service inside into the OnDemand injectable
    return $c['factory']->protect(ServiceH::class);
};

/** @var OnDemand $serviceH */
$serviceH = $container->get('serviceH');
$inst     = $serviceH->newInstance('foo', 'bar');

// or if you want to treat them as singleton
$inst     = $serviceH->getInstance('foo', 'bar');

/** @var ServiceE $serviceE */
$serviceE = $container->get('serviceE');

$svc = $serviceE->getService();

Non injectables (3rd party services)

If you want to inject services not implementing the Injectable interface (http-clients, etc.), you can register them using the OnDemand service.

class ServiceJ implements Injectable
{
    /** @var OnDemand */
    protected $foreignService = null;

    private function setForeignServices(OnDemand $foreignService)
    {
        $this->foreignService = $foreignService;
    }
    
    public function getForeignService()
    {
        return $this->foreignService->getInstance();
    }
}

$container['foreignService'] = function ($c) {
    return $c['factory']->protect(stdClass::class);
};
$container['serviceJ'] = function ($c) {
    return $c['factory']->get(ServiceJ::class);
};

/** @var ServiceJ $serviceJ */
$serviceJ = $container->get('serviceJ');

$std = $serviceJ->getForeignService();

Reusability with traits

Traits are very handy, if you do not want to duplicate the code when injecting the same service again and again.

Write a Trait with the property, geter and seter

use Stk\Service\OnDemand;

trait DependsOnServiceB 
{
    /** @var OnDemand */
    protected $_serviceB;

    private function setServiceB(OnDemand $serviceB)
    {
        $this->_serviceB = $serviceB;

        return $this;
    }

    /**
     * @return ServiceB
     */
    protected function serviceB()
    {
        return $this->_serviceB->getInstance();
    }
}

...

class ServiceJ implements Injectable
{
    use DependsOnServiceB;
}

mbretter/stk-di 适用场景与选型建议

mbretter/stk-di 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.21k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2019 年 07 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 mbretter/stk-di 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 3.21k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 12
  • 依赖项目数: 7
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2019-07-22