romeoz/rock-di

小型且灵活的 PHP 依赖注入库

0.14.0 2015-11-09 06:34 UTC

This package is not auto-updated.

Last update: 2024-09-24 03:45:11 UTC


README

Latest Stable Version Total Downloads Build Status HHVM Status Coverage Status License

特性

  • 服务定位器
  • 构造函数注入
  • 支持单例
  • 独立模块/组件,适用于 Rock 框架

安装

从命令行

composer require romeoz/rock-di

在您的 composer.json 中

{
    "require": {
        "romeoz/rock-di": "*"
    }
}

快速开始

namespace test;

use rock\di\Container;

class Foo 
{
    
}

$config = [
    'class' => '\test\Foo', 
    // 'singleton' => true,   // if you want to return singleton
 ];
$alias = 'foo' ;  // short alias
Container::register($alias, $config);

$foo = Container::load('foo');

####构造函数注入

namespace test;

use rock\di\Container;

class Foo 
{
    
}

class Bar 
{
    public $foo;
        
    public function __construct(Foo $foo)
    {
        $this->foo = $foo;
    }
}

$config = [
    'class' => '\test\Foo',
 ];
Container::register('foo' , $config);

$config = [
    'class' => '\test\Bar',
 ];
Container::register('bar' , $config);

$bar = Container::load('bar');
$bar->foo instanceof Bar; // output: true

####配置属性

namespace test;

use rock\di\Container;
use rock\base\ObjectInterface;
use rock\base\ObjectTrait;

class Foo implements ObjectInterface
{
    use ObjectTrait;
    
    public $name;
}

$config = [
    'class' => '\test\Foo', 
    
    // properties
    'name' => 'Tom'
 ];

Container::register('foo', $config);

$foo = Container::load('foo');

echo $foo->name; // output: Tom 

通过设置器和获取器配置属性

namespace test;

use rock\di\Container;
use rock\base\ObjectInterface;
use rock\base\ObjectTrait;

class Foo implements ObjectInterface
{
    use ObjectTrait;
    
    private $name;
    
    public function setName($name)
    {
        $this->name = $name;
    }
    
    public function getName()
    {
        return $this->name;
    }
    
}

$config = [
    'class' => '\test\Foo', 
    
    // properties
    'name' => 'Tom'
 ];

Container::register('foo', $config);

$foo = Container::load('foo');

echo $foo->name; // output: Tom 

需求

  • PHP 5.4+

许可证

Rock 依赖注入是开源软件,根据 MIT 许可证 发布。