【发布时间】:2015-12-18 22:55:48
【问题描述】:
众所周知,包装类的重点是封装另一个类或组件的功能。这是一个简单的类,它包装了一小部分 PHP Predis 库:
class CacheWrapper {
private $client;
public function __construct(){
$this->client = new Predis\Client();
}
public function set($key, $value){
$this->client->set($key, $value);
}
public function get($key){
return $this->client->get($key);
}
}
这里是使用这个包装类的简单代码:
$client = new CacheWrapper();
echo $client->get('key1');
这个类可以完美工作的地方是它在类内部创建依赖项的问题,我想通过将依赖项注入类而不是让类创建它的依赖项来避免这个问题,因此包装类看起来像这样:
class CacheWrapper {
private $client;
public function __construct(Predis\Client $predisObj){
$this->client = $predisObj;
}
public function set($key, $value){
$this->client->set($key, $value);
}
public function get($key){
return $this->client->get($key);
}
}
所以我必须编写以下代码来使用包装类:
$predis = new Predis\Client();
$client = new CacheWrapper($predis);
echo $client->get('key1');
但我认为没有必要使用包装类,因为我仍然在我的代码中使用原始类。所以我的问题是:依赖注入和包装类概念是否相互矛盾,不能一起使用,解决此类问题的最佳方法是什么?
【问题讨论】:
标签: php design-patterns dependency-injection wrapper