我没有发现您引用的博客文章非常有趣或富有洞察力。
你所描述的似乎更像是装饰者 http://en.wikipedia.org/wiki/Decorator_pattern比任何与依赖注入有关的事情都重要。依赖注入是how你构建你的对象图,而不是它们的state一旦建成。
也就是说,我建议采用装饰器模式并运行它。
interface PostInterface
{
public function title();
}
class PostModel implements PostInterface
{
public function title()
{
return $this->title;
}
}
class PostViewHelper implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->post->title();
}
}
class PostFilter implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->filter($this->post->title());
}
protected function filter($str)
{
return "FILTERED:$str";
}
}
您只需使用任何 DI 框架即可构建此对象图,如下所示:
$post = new PostFilter(new PostViewHelper($model)));
我在构建复杂的嵌套对象时经常使用这种方法。
您可能遇到的一个问题是在您的程序中定义“太多”函数PostInterface
。它可以是一个pain必须在每个装饰器类中实现这些。我利用 PHP 魔法函数来解决这个问题。
interface PostInterface
{
/**
* Minimal interface. This is the accessor
* for the unique ID of this Post.
*/
public function getId();
}
class SomeDecoratedPost implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->_post = $post;
}
public function getId()
{
return $this->_post->getId();
}
/**
* The following magic functions proxy all
* calls back to the decorated Post
*/
public function __call($name, $arguments)
{
return call_user_func_array(array($this->_post, $name), $arguments);
}
public function __get($name)
{
return $this->_post->get($name);
}
public function __set($name, $value)
{
$this->_post->__set($name, $value);
}
public function __isset($name)
{
return $this->_post->__isset($name);
}
public function __unset($name)
{
$this->_post->__unset($name);
}
}
使用这种类型的装饰器,我可以有选择地重写提供装饰功能所需的任何方法。我没有覆盖的任何内容都会传递回底层对象。在维护底层对象的接口的同时,可以发生多个装饰。