有没有理由将POST数组依赖注入控制器?
例如,说我有这个:
class Controller
{
function __construct()
{
$this->coverPageChoice = $_POST['coverpage'];
$this->printNameplates = $_POST['print_nameplates'];
$this->commentsOnSeparatePage = $_POST['comments_on_new_page'];
}
}
将$ _POST数组注入构造函数是否有任何好处,如下所示:
class Controller
{
function __construct(array $input)
{
$this->coverPageChoice = $input['coverpage'];
$this->printNameplates = $input['print_nameplates'];
$this->commentsOnSeparatePage = $input['comments_on_new_page'];
}
}
答案 0 :(得分:2)
当然,第二个更好,例如提高可测试性。而且为了避免来自外部世界的依赖(是的,来自PHP本身),因此,它改进了封装。
最好通过某种类来抽象$ _POST,以便对它进行一致的访问,例如Symfony中的Request:https://symfony.com/doc/current/components/http_foundation.html#request