PHP MVC:在控制器和视图之间共享模型

PHP MVC: Share model between controller and view

我正在开发我的 PHP (H)MVC 项目,在该项目中我将视图与控制器分开 - 如答案 How should a model be structured in MVC? 中所示。他们的关系是1:1,所以他们有相同的"actions"。因此,在 bootstrap.php 中,在我实例化它们之后调用:

// ... Controller and view are already instantiated.
call_user_func_array(array($controller, $actionName), $actionParameters);
call_user_func_array(array($view, $actionName), $actionParameters);

假设一个控制器和一个视图变成了一个模型(域对象)作为构造函数参数。 使用 Auryn 依赖注入容器,我尝试在控制器和视图之间共享相同的模型实例,而不是事先实例化它。例如。在控制器和视图实例化发生在 bootstrap.php.

之前

在他的回答中,tereško 描述了 model/service 工厂的使用。但作为 "Note" 他说:

...A much better implementation would have the DI container (like Auryn) to create controllers and views, with only the required services, instead of using a factory.

我的问题是:我可以在没有模型工厂的情况下使用依赖注入容器实现这个功能吗? 我有点陷入这项任务,我真的不知道这是否有可能。 谢谢。

是的,你可以。

但这有点繁琐。您基本上需要将服务设置为 "shared":

<?php
$injector->define('MailerService', [
    ':server' => 'fak.it',
    ':port' => '443',
]);
$injector->share('MailerService');

$controller = $injector->make('FooBarController');

这假设您的控制器是这样定义的:

<?php
class FooBarController 
{
    public function __construct(MailerService $service) 
    {
        // ...
    }
}

在这方面,Symfony 的独立 DI component 更容易使用,因为您可以将这种配置放在 json 或 yaml 文件中。

P.S. 你可能应该将你的用户输入抽象为某种 Request 对象蚂蚁在每次方法调用时将其传递到你的控制器中。

有点像这样:

<?php
$request = new Request( .. something here maybe .. );
$controller->action($request);

制作更漂亮的代码:)