crishellco/rivet-ioc

一个简单的PHP自动装配IoC容器

1.1.3 2017-12-29 22:15 UTC

This package is not auto-updated.

Last update: 2024-09-28 18:21:24 UTC


README

Build Status

RivetIoc 是一个用于PHP的自动装配(零配置)IoC容器,便于轻松管理类依赖。它具有使用反射自动装配依赖以及手动注册进行依赖注入的功能。

特性

  • 自动装配(零配置)依赖注入
    • 递归依赖注入
  • 手动注册以进行更复杂的依赖管理
  • 定位器特质,公开常用的RivetIoc\Ioc方法

入门指南

安装

$ composer require crishellco/rivet-ioc

系统要求

PHP >= 5.4.0

文档

自动装配

使用类型提示定义你的类

namespace App;
class DbDriver
{
    ...
}
namespace App;
class Db
{
    protected $driver;

    public function __construct(DbDriver $driver)
    {
        $this->driver = $driver;
    }
}
namespace App\Services;
class UserService
{
    protected $db;

    public function __construct(Db $db)
    {
        $this->db = $db;
    }
}

使用RivetIoc创建新的类实例

RivetIoc 将使用构造函数类型提示自动创建和注入依赖

$userService = \RivetIoc\Ioc::instance()->make('App\Services\UserService');

// Or use the helper function...
$userService = rivet_make('App\Services\UserService');

手动依赖注册

在你的应用程序引导程序中注册你的依赖

\RivetIoc\Ioc::instance()->register('App\Db', function() {
    $mysqli = new mysqli('localhost', 'username', 'password', 'mydb');
    $db = new App\Db($mysqli);

    return $db;
});

使用RivetIoc创建新的类实例

RivetIoc 将使用注册的闭包来创建和注入依赖

$db = \RivetIoc\Ioc::instance()->make('App\Db');

// Or use the helper function...
$db = rivet_make('App\Db');

忘记手动注册的依赖

register_shutdown_function(function() {
    \RivetIoc\Ioc::instance()->forget('App\Db');
});

定位器特质

在一个类中使用RivetIoc\Traits\Locator特质以访问常用的RivetIoc\Ioc方法

  • make
  • register
  • forget
namespace App\Services;
class UserService
{
    use \RivetIoc\Traits\Locator;

    protected $dao;

    public function __construct()
    {
        $this->dao = $this->make('App\Doa\UserDao');

        // Or use the helper function...
        $this->dao = rivet_make('App\Doa\UserDao');
    }
}

如何贡献

拉取请求

  1. 分支RivetIoc存储库
  2. 为每个功能或改进创建一个新的分支
  3. 从每个功能分支向 develop 分支发送拉取请求