IOC容器和PSR-11

什么是IOC容器

深入理解DIP、IoC、DI以及IoC容器

起草中PSR-11服务容器接口

IOC容器的实现

pimple

auryn

nette DI

PHP-DI

Acclimate

应用举例

我们以PHP-DI来写demo

namespace demo\ioc\Classes;

use demo\ioc\Interfaces\SoldierInterface;
use demo\ioc\Interfaces\Weapon;

class Soldier implements SoldierInterface
{
    protected $weapon;

    public function __construct(Weapon $weapon)
    {
        $this->weapon = $weapon;
    }

    public function attack($target)
    {
        $this->weapon->attack($target);
    }
}
namespace demo\ioc\Classes;

use demo\ioc\Interfaces\Weapon;

class Sword implements Weapon
{
    protected $locate;

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

    public function attack($target)
    {
        echo "在{$target}的身上划开了巨大的伤口,本武器在{$this->locate}生产".PHP_EOL;
    }
}
namespace demo\ioc\Interfaces;

interface SoldierInterface
{
    public function attack($target);
}
namespace demo\ioc\Interfaces;

interface Weapon
{
    public function attack($target);
}
require __DIR__.'/vendor/autoload.php';

$weapon = new Sword('上海');
$solder = new Soldier($weapon);
$solder->attack("小怪兽");
echo nl2br(PHP_EOL);
$builder = new ContainerBuilder();

$dependence = [
    'Soldier'=> autowire(Soldier::class),
    Weapon::class => function(ContainerInterface $c){
        return new Sword($c->get('locate'));
    },
    'locate'=>value('北京')
];

$builder->addDefinitions($dependence);

$container = $builder->build();

$solder = $container->get('Soldier');

$solder->attack("灭霸");

引入了以下依赖

"require": {
        "php":">=7.0.0",
        "php-di/php-di": "^6.0"
    },

评论

captcha