Son*_*ngo 7 php oop dependency-injection zend-framework
维基百科引用的DI的定义指出:
A.高级模块不应该依赖于低级模块.两者都应该取决于抽象.B.抽象不应该依赖于细节.细节应取决于抽象.
我正在尝试将该原则应用于我的代码:
class Printer{
private $logger;
function __construct(Zend_Log $logger){
$this->logger=$logger;
}
function print(){
//Some code
$this->logger->log('Logger in action ;)');
}
}
Run Code Online (Sandbox Code Playgroud)
既然为什么Printer类依赖于Zend_Log哪个既不是抽象类也不是接口,那么我就违反了依赖性倒置原则.
如何知道Zend_Log不扩展抽象类也不实现接口?
最简单的方法是使用接口适配器,例如创建打印机应该在接口中使用的API,然后在适配器中为Zend_Log组件实现该接口.将具体的适配器传递给打印机.然后打印机将依赖于PrinterLog而不是具体的Zend_Log.
interface PrinterLog
{
public function log($whatever);
}
class ZendPrinterLogAdapter implements PrinterLog
{
private $logger;
public function __construct(Zend_Log $logger)
{
$this->logger = $logger
}
public function log($whatever)
{
// delegate call to $this->logger
}
}
class Printer
{
private $logger;
function __construct(PrinterLog $logger)
{
$this->logger = $logger;
}
}
$printer = new Printer(new ZendPrinterLogAdapter(new Zend_Log));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
328 次 |
| 最近记录: |