duanmibei1929 2013-10-12 23:18
浏览 31
已采纳

控制器和视图之间的1:1关系服务的目的是什么?

I am looking for a better explanation of the view layer in MCV, and in particular how the flow in the program goes from controller to view, with focus on the state of the model when using a 1:1 relationship between controller and view.

In all examples I have seen data is being forwarded to the view from the controller, and the view does nothing specific that would require a specific view to be written for a specific controller. Have I misunderstood the 1:1 relationship mantra? The latest example I found was posted here some days back: https://stackoverflow.com/a/18983927/1681418

class View
{
   public function render($templateFile, array $vars = array())
   {
      ob_start();
      extract($vars);
      require($templateFile);

      return ob_get_clean();
   }
}

I have tried to create specific view classes for each controller, and I currently have a view that extracts all data from the model as it requires it. It is clean in the sense that I have a very defined do-stuff-to-the-model section (=controller) and a read-only-from-model section (=view). I have however a few shortcomings that I have yet to find a tidy solution for, namely:

  • Where should the template file be selected?
  • How does the view get to know about errors in the model?
  • How does the view get to know about successful or unsuccessful command/action in controller?
  • How do I change view when there is an error? Or how do I properly do my routing for the cases when a user state changes.

I have no trouble rendering correct output on my page, but my current approach feels wrong. **Anyone got an example of a view that uses domain driven design with the model as a layer, not a class? **

This answer is very similar to what I usually find, and I do not understand how this approach uses or requires a 1:1 relationship.

I am mostly looking for examples, not code review, but I have in any case extracted some pieces of my code below for examples. Here I am calling the controller via a dispatcher for access control and routing, then the view via the same dispatcher to again check for access. The view in turns calls different presentation objects that assigns data to the template engine if http request, json if ajax request.

class Controller
{
    public function login()
    {
        $this->serviceFactory
            ->build('recognition')
            ->authenticate($this->request->username, $this->request->password);
    }
}

class View
{
    public function login()
    {

        /** Prepare server response (i.e. state of the model) */
        $this->presentationObjectFactory
            ->build('serverresponse', true)
            ->setPresentationName('success')
            ->assignData($this->serviceFactory->build('modelLog')->getModelResponse('success'));

        /** Get current visitor information */
        $this->presentationObjectFactory
            ->build('visitor', true)
            ->assignData($this->serviceFactory->build('recognition')->getCurrentVisitor()); 

        return $this->serviceFactory->build('recognition')->getCurrentVisitor()->isLoggedIn() ? 
                    $this->indexAction() : /* Reroute to index of view */
                    $this->display('login.html'); /* Show the login template when unsuccesful login*/
    }
}

class PresentationObject
{
    public function assignData(Collection $visitors)
    {
        $dateformat = new DateFormat();
        $dateTime = new \Datetime();

        foreach($visitors as $visitor)
        {
            $dateTime->setTimestamp($visitor->timestamp);

            $this->assign_block_vars('visitor', array(
                'ID'                => $visitor->id,
                'USERNAME'          => $visitor->user->Username,
                'IP'                => $visitor->remote_addr,
                'HTTP_USER_AGENT'   => $visitor->http_user_agent,
                'LAST_SEEN_ONLINE'  => ucfirst($dateformat->formatDateDiff($dateTime)),
                'DEVICE'            => $visitor->getDevice(),
                'PLATFORM'          => $visitor->getPlatform(), 
                'BROWSER'           => $visitor->getBrowser(),  
            ));
        }
    }
}

My knowledge and understanding of MVC and domain driven design is strongly influenced by the user tereško, but I have probably misunderstood something on the View part of this explanations...

  • 写回答

1条回答 默认 最新

  • douyao1856 2013-10-12 23:49
    关注

    What purpose does a 1:1 relationship between controller and view serve?

    There is no need for a strict 1:1 rule if the view can be applied in multiple workflow contexts / controllers / models. Keeping a view and controller separate, even if they are only used together and can be merged, is a best practice for a clear separation of responsibilities. It also makes it easier to swap and share views later.

    Where should the template file be selected?

    In your case you have a View class, so it should be defined there. In some systems the template is the view and is often selected in the controller or configuration files.

    How does the view get to know about errors in the model? How does the view get to know about successful or unsuccessful command/action in controller?

    In some architectures the models return their issues to the controller during updates or any other actions. In the controller I usually add any problems to a user message stack. Then in the view I output those messages to the user.

    How do I change view when there is an error? Or how do I properly do my routing for the cases when a user state changes.

    This I've seen handled in quite a few different ways. The most robust solution is for your controller to pass the next workflow steps to the view. The view should basically stay as agnostic as possible to any business logic.

    Any example code would be too long and elaborate for SO. I would start with good MVC framework tutorials:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog