我正在尝试理解传递变量的确切工作方式。
我已经设置了一个控制器:
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>
如何为视图设置标题?我应该在控制器中“公开”这个var,并在构建模型时使用它来在我的视图文件中使用吗?
答案 0 :(得分:1)
您的设计存在问题但忘记这些是您可以这样做的方式。
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');
答案 1 :(得分:1)
是什么让您觉得您正在实施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
将在控制器和视图之间共享,因为它是您与模型层交互的方式。这也为您提供了一种只初始化每个服务一次的方法,而不会产生对全局状态的依赖。
我应该在控制器中'公开'这个var,并在构建模型时使用它来在我的视图文件中使用吗?
没有
模型层(是的,它应该是图层而不是类)不应该从表示层的实现中了解任何内容。实际上,视图也不应该知道控制器。
实际上,在OOP中使用公共变量被认为是一种不好的做法(除非您正在创建数据结构..想想:像二叉树之类的东西)。它会使您的代码为leak encapsulation。
我正在尝试理解传递变量的确切工作方式。
这是OOP的基础知识。如果你对OOP概念,实践和方法没有很好的掌握,你不应该使用像MVC模式这样的高级结构。
查找称为“依赖注入”的内容。