将变量从控制器通过模型传递到视图文件


pass a variable from controller, through a model to a view file

我试图了解传递变量的确切工作原理。

我已经设置了一个控制器:

class indexController
{
    public function calling()
    {
        $route = new Route():
        $route->title = 'Register user';
        $route->getview('users','register');
    }
}

还有一个模型:

class Route
{
    public function getview($module,$filename)
    {
        require_once('templates/'.$module.'/'.$filename.'.phtml');
    }
}

还有一个视图文件,它有这样的东西:

<div class="title"><?php echo $this->title; ?></div>

如何设置视图的标题?我是否应该在控制器中"公开"这个变量,并在构建模型以在我的视图文件中使用的模型时获取它?

你的设计有问题,但忘记这些是你可以做到的。

public function var( $var, $val ) {
    $this->vars[$var] = $val; // should disallow _view as a $var
}
public function getview($module,$filename)
{
    $_view = 'templates/'.$module.'/'.$filename.'.phtml';
    extract( $this->vars );  //creates variables for 
    require_once( $_view );
}

像这样使用它

    $route = new Route():
    $route->var( 'title', 'Register user' );
    $route->getview('users','register');

是什么给你的印象是你正在实施 MVC?因为从立场来看,您似乎已经混淆了模式每个部分的责任。

这是基础知识..

MVC是一种架构设计模式,是SoC原则的表达。它将模型层(负责实现域业务逻辑(与表示层分开。在表示层中,它将处理用户输入的部分(控制器(与生成用户界面(视图(的逻辑分开。

将此模式应用于 Web 时,信息流如下所示:

  • 控制器接收来自用户的请求
  • 控制器更改模型层和(可能(当前视图的状态
  • 查看来自模型层的请求必要信息
  • 视图生成对用户的响应

你那里的不是视图,而只是一个模板。你在那里拥有的不是模型,而只是一个类。

现在你问:

如何设置视图的标题?

您的视图应从模型层请求所需的信息:

namespace Views;
class Doclument 
{
    // ... some code
    public function foobar()
    {
        $library = $this->serviceFactory->acquire('Library');
        $title = $library->getCurrentDocument('title');
        $content = $library->getCurrentDocument('content');
        
        $this->template['main']->assign([
           'title' => $title,
           'body'  => $content,
        ]);
    }
    // ... some more code 
    public function render()
    {
       /*
           if any templates have been initialized,
           here you would put code for combining them and
           return html (or some other format)
       */
    }
}

当然,您需要知道用户希望查看哪个文档..应该在控制器中完成:

namespace Controllers;
class Document
{
    // ... again, some code, that's not important here
    public function getFoobar( $request )
    {
        $library = $this->serviceFactory->acquire('Library');
        $library->useLanguage( $request->getParameter('lang') );
        $library->locateDocument( $request->getParameter('id') );
    }
}

$serviceFactory将在控制器和视图之间共享,因为这是您与模型层交互的方式。这也为您提供了一种仅初始化每个服务一次的方法,而不会创建对全局状态的依赖关系。

我是否应该在控制器中"公开"这个变量,并在构建模型以在我的视图文件中使用的模型时获取它?

不。

模型层(是的,它应该是层而不是(不应该从表示层的实现中了解任何东西。实际上,视图也不应该知道控制器的。

实际上,在 OOP 中使用公共变量被认为是一种不好的做法(除非您正在创建数据结构.. 想想:像二叉树这样的东西(。它会导致代码泄漏封装。

附言

我试图了解传递变量的确切工作原理。

这是 OOP 的基础。如果你没有很好地掌握 OOP 概念、实践和方法,你不应该玩弄像 MVC 模式这样的高级结构。

查找称为"依赖注入"的东西。