2017 © Pedro Peláez
 

library sim-di

simple dependency inject container

image

zean/sim-di

simple dependency inject container

  • Monday, July 31, 2017
  • by ZhengZean
  • Repository
  • 1 Watchers
  • 1 Stars
  • 2 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 2 Versions
  • 0 % Grown

The README.md

SimDI

一个简单的PHP依赖注入框架,支持autowire。, (*1)

附上之前写的一篇文: 用PHP撸一个DI容器, (*2)

安装

composer require zean/sim-di

使用

  1. 不使用面向接口编程风格, (*3)

    假如有Car和Driver两个类,Driver依赖Car, (*4)

    class Car
    {
        protected $name = '汽车';
    
        public function getName()
        {
            return $this->name;
        }
    }
    
    class Driver
    {
        protected $car;
    
        public function __construct(Car $car)
        {
            $this->car = $car;
        }
    
        public function drive()
        {
            return '驾驶' . $this->car->getName();
        }
    }
    

    当我们需要Diver实例的时候,这时候我们只需要让容器创建,容器会自动注入Car实例, (*5)

    $app = \SimDI\Container::getInstance();
    $driver = $app->get(Driver::class);
    echo $driver->drive();
    

output:驾驶汽车, (*6)

  1. 使用面向接口编程风格

假如我们用面向接口的方式来,我稍微修改一下上面的代码:, (*7)

abstract class Car
{
    protected $name = '汽车';

    public function getName()
    {
        return $this->name;
    }
}

```php interface Driveable { public function run(); }, (*8)

```php
class Benz extends Car implements Driveable
{
    protected $name = '奔驰';

    public function run()
    {
        return $this->getName() . '启动了!';
    }
}

```php class Driver { protected $car;, (*9)

public function __construct(Driveable $car)
{
    $this->car = $car;
}

public function drive()
{
    return '驾驶' . $this->car->run();
}

}, (*10)

面向接口编程时需要有一个配置来指定interface和实现类的对应关系,如下:

```php
$config = [
    Driveable::class => Benz::class,
];

然后在创建容器的时候我们使用上述配置:, (*11)

$app = \SimDI\Container::getInstance($config);
$driver = $app->get(Driver::class);
echo $driver->drive();

output:驾驶奔驰启动了!, (*12)

The Versions

31/07 2017

dev-master

9999999-dev

simple dependency inject container

  Sources   Download

MIT

The Requires

 

The Development Requires

by Avatar ZhengZean

25/07 2017

v1.0

1.0.0.0

simple dependency inject container

  Sources   Download

MIT

The Requires

 

The Development Requires

by Avatar ZhengZean