美文网首页
IOC控制反转和DI依赖注入

IOC控制反转和DI依赖注入

作者: 长安猎人 | 来源:发表于2018-08-07 00:56 被阅读0次

创建被调用者的工作不再由调用者来完成,因此称为控制反转;

<?php

interface IDeviceWriter {
    public function saveToDevice();
}

class Business {
    private $writer;

    public function setWriter($writer) {
        $this->writer = $writer;
    }

    public function save() {
        $this->writer->saveToDevice();
    }
}

class FloppyWriter implements IDeviceWriter {
    public function saveToDevice()
    {
        echo __METHOD__ . PHP_EOL;
    }
}

class UsbWriter implements IDeviceWriter {
    public function saveToDevice()
    {
        echo __METHOD__ . PHP_EOL;
    }
}

$biz = new Business();
$biz->setWriter(new FloppyWriter());
$biz->save();

$biz->setWriter(new UsbWriter());
$biz->save();

参考资料:https://segmentfault.com/a/1190000002411255

相关文章

网友评论

      本文标题:IOC控制反转和DI依赖注入

      本文链接:https://www.haomeiwen.com/subject/omwnvftx.html