【发布时间】:2014-07-31 20:08:45
【问题描述】:
参考此评论,
当一个类有很长的参数列表时,它可以是一个“代码 闻到“你的班级试图做的太多而且可能没有 遵循单一责任原则。如果你的班级正在尝试 做太多,考虑将你的代码重构为一些 相互消耗的小类。
我应该如何处理下面的这个控制器类 - 它是“试图做太多”吗?
class Controller
{
public $template;
public $translation;
public $auth;
public $article;
public $nav;
public function __construct(Database $connection, $template)
{
$this->template = $template;
$this->translation = new Translator($connection);
$this->nav = new Nav($connection);
$this->article = new Article($connection);
$this->auth = new Auth($connection);
}
public function getHtml()
{
if(isset($_REQUEST['url']))
{
$item = $this->article->getRow(['url' => 'home','is_admin' => $this->auth->is_admin]);
include $this->template->path;
}
}
}
我如何将它分解为更小的类 - 如果它是一个控制器,它包含我需要输出页面的这些基本类?
我应该怎么做才能遵循dependency injection的原则?
【问题讨论】:
-
两个参数就好了。然而,所有这些实例化都应该是构造函数或单独设置器的参数。
-
@halfer:谢谢。是的
all those instantiations在我的控制器中很难看,我怎样才能让它们分开设置器,以便我可以在我的控制器类中调用它们? -
@halfer:如果我把它们设为
parameters either to the constructor,那么它是a class has a very long list of arguments, it can be a "code smell" that your class is trying to do too much and possibly not following the single responsibility principle.不是吗? -
(虽然代码格式看起来不错,但作为一般的荧光笔,无论是在问题还是在 cmets 中,它的可读性都不是很好。对这里编辑问题感兴趣的人倾向于建议它只适用于内联代码)。跨度>
-
是的,不要将它们全部添加到构造函数中。构造函数可能有 2 或 3 个对对象的构造至关重要的参数,其余的应该在 setter 中。 setter 是一个接受参数并将其存储在属性中的函数,可能在验证它之后。如果它们是类或数组,您也可以在 PHP 中对它们进行类型提示。
标签: model-view-controller dependency-injection solid-principles single-responsibility-principle php-5.5