【发布时间】:2013-06-10 17:45:52
【问题描述】:
我正在创建一个用于学习/教学目的的 mvc 结构,到目前为止,我可以设置该结构和一个控制器以及作为模板系统的树枝。
结构是:
- index.php
- 控制器/
- error.php
- error.php
- inc/
- controller_base.php
- view_manager.php
- controller_base.php
- 观看次数/
- .cache/
- 错误/
- view.html
- view.html
所以:
- 索引实例化 twig 自动加载器(和 spl_register 的 mvc 自动加载器)。
- 索引实例化错误控制器继承controller_base。
- controller_base 持有 view_manager。
- 错误调用 view_manager 以显示
error/view.html而我在浏览器上得到的唯一内容是error/view.html。
apache 日志中没有错误。 (error_reporting(E_ALL))
Twig 缓存文件创建正确,但内容对我来说看起来不太好:
protected function doDisplay(array $context, array $blocks = array()) {
// line 1
echo "error/view.html";
}
任何人都知道为什么,以及如何打印实际视图?
提前致谢。
代码:
index.php:声明自动加载器
function __autoload($class_name)
{
if(file_exists("controllers/$class_name.php")):
include strtolower("controllers/$class_name.php");
elseif(file_exists("models/$class_name.php")):
include strtolower("models/$class_name.php");
elseif(file_exists("inc/$class_name.php")):
include strtolower("inc/$class_name.php");
endif;
}
spl_autoload_register('__autoload');
require_once 'vendor/autoload.php';
Twig_Autoloader::register();已被避免,因为 Twig 安装是由作曲家完成的。 添加它不会带来任何变化。
error.php(控制器):被调用的方法。
public function show($param)
{
$this->viewMng->display(get_class().$data['view'], array())
}
controller_base.php:
class base
{
protected $viewMng;
public function __construct()
{
$this->viewMng = new viewmanager();
}
}
viewmanager.php:全班
class viewmanager {
private $twig;
protected $template_dir = 'views/';
protected $cache_dir = 'views/.cache';
// protected $vars = array();
public function __construct($template_dir = null) {
if ($template_dir !== null) {
// Check here whether this directory really exists
$this->template_dir = $template_dir;
}
$loader = new Twig_Loader_String($this->template_dir);
$this->twig = new Twig_Environment($loader, array(
'cache' => $this->cache_dir));
}
public function render($template_file, $data = array()) {
if (!file_exists($this->template_dir.$template_file)) {
throw new Exception('no template file ' . $template_file . ' present in directory ' . $this->template_dir);
}
return $this->twig->render($template_file, $data);
}
public function display($template_file, $data) {
if (!file_exists($this->template_dir.$template_file)) {
throw new Exception('no template file ' . $template_file . ' present in directory ' . $this->template_dir);
}
$tmpl = ($this->twig->loadTemplate($template_file));//print_r($tmpl);
$tmpl->display($data);
}
}
view.html:
<html><body> Hello </body></html>
【问题讨论】:
-
能否贴出“error call view_manager to display the error/view.html”的代码?
-
对不起,我已经添加了所有相关代码。如果你还有什么想看的,尽管问。感谢您的观看!
-
当您致电
echo $this->viewMng->render(get_class().$data['view'], array())时会发生什么?还有为什么有括号:$tmpl = ($this->twig->loadTemplate($template_file));? -
渲染函数产生完全相同的结果。没有括号的理由。可能是由于编辑和尝试了不同的选项。他们肯定会在最后消失。还尝试将模板放在视图根文件夹中,结果相同。这不是路径上的问题,否则会产生异常。对问题进行了编辑:“编译文件”中的 doDisplay 仅包含“echo 'error/view.html';”。不知道这是否正常,但也许有助于解决问题。
标签: php model-view-controller twig