MVC php程序中的$ view是否正确使用了全局变量? [英] Is $view in an MVC php program a proper use of global variables?

查看:99
本文介绍了MVC php程序中的$ view是否正确使用了全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白全局变量应该避免一般。作为一名初学者,我试图了解是否在遵循MVC原则构建的动态Web程序中创建$ view变量全局变量是全局变量是个好主意的情况之一。



在我的程序中,我创建了index.php中的$ view(作为一个包含空数组的对象),并在使用它的控制器中将其变为全局。



谢谢!

JDelage

解决方案


在我的程序中,我创建了$ view作为index.php中的一个空数组(),并在使用它的控制器中将其变为全局变量。


为什么?如果你的控制器需要 $ view 然后通过构造函数或setter传入。始终可以通过使用依赖注入来解决Globals上的依赖关系。

  // index.php 
$ view = array();
$ controller = new Controller($ view);
$ controller-> doAction();

另外,请重新考虑View是否只是一个数组。该视图必须在某个时刻呈现。渲染是我在View上看到的一个责任。一个数组无法呈现自己,所以我假设你在别处做它。这违反了单一责任原则。我宁愿按照( simplified )的方式做一些事情:

  // index.php 
$ view = new View;
$ controller = new Controller($ view);
$ controller-> doAction();

// controller.php
...
public function doAction()
{
...
$ this->视图 - > setTemplate( '/路径/到/模板');
$ this-> view-> setVar('foo','bar');
$ this-> view-> render();
}
...


I understand that global variables should be avoided generally. As a beginner, I'm trying to understand whether making a $view variable global in a dynamic web program built following MVC principles is one of those cases where globals are a good idea.

In my program, I create the $view (as an object that contains an empty array) in index.php, and turn it into a global in the controllers that use it.

Thanks!

JDelage

解决方案

In my program, I create the $view as an empty array() in index.php, and turn it into a global in the controllers that use it.

Why? If you controller needs the $view then just pass it in via the constructor or a setter. Dependencies on Globals can always be resolved by using Dependency Injection.

// index.php
$view = array();
$controller = new Controller($view);
$controller->doAction();

Also, please reconsider if the View should be just an array. The View has to be rendered at some point. Rendering is a responsibility I'd see on the View. An array cannot render itself, so I assume you are doing it elsewhere. That would be a violation of the Single Responsibility Principle. I'd rather do something along the lines of (simplified):

// index.php
$view = new View;
$controller = new Controller($view);
$controller->doAction();

// controller.php
...
public function doAction()
{
    ...
    $this->view->setTemplate('/path/to/template');
    $this->view->setVar('foo', 'bar');
    $this->view->render();
}
...

这篇关于MVC php程序中的$ view是否正确使用了全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆