用PHP渲染视图 [英] Render a view in PHP

查看:250
本文介绍了用PHP渲染视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写自己的MVC框架,并已加入视图渲染器.我将控制器中的vars设置为View对象,然后通过.phtml脚本中的echo $ this-> myvar访问vars.

I am writing my own MVC framework and has come to the view renderer. I am setting vars in my controller to a View object and then access vars by echo $this->myvar in the .phtml script.

在我的default.phtml文件中,我调用方法$ this-> content()输出视图脚本.

In my default.phtml I call the method $this->content() to output the viewscript.

这就是我现在做的方式.这是这样做的正确方法吗?

This is the way I do it now. Is this a proper way to do that?

class View extends Object {

    protected $_front;

    public function __construct(Front $front) {
        $this->_front = $front;
    }

    public function render() {                
        ob_start();
        require APPLICATION_PATH . '/layouts/default.phtml' ;            
        ob_end_flush();
    }

    public function content() {
        require APPLICATION_PATH . '/views/' . $this->_front->getControllerName() . '/' . $this->_front->getActionName() . '.phtml' ;
    }

}

推荐答案

以下是我的操作方法示例:

Here's an example of how i did it :

<?php


class View
{
private $data = array();

private $render = FALSE;

public function __construct($template)
{
    try {
        $file = ROOT . '/templates/' . strtolower($template) . '.php';

        if (file_exists($file)) {
            $this->render = $file;
        } else {
            throw new customException('Template ' . $template . ' not found!');
        }
    }
    catch (customException $e) {
        echo $e->errorMessage();
    }
}

public function assign($variable, $value)
{
    $this->data[$variable] = $value;
}

public function __destruct()
{
    extract($this->data);
    include($this->render);

}
}
?>

我使用控制器中的assign函数来分配变量,然后在析构函数中提取该数组以使其成为视图中的局部变量.

I use the assign function from out my controller to assign variables, and in the destructor i extract that array to make them local variables in the view.

如果愿意,可以随时使用它,我希望它能使您了解如何操作

Feel free to use this if you want, i hope it gives you an idea on how you can do it

这是一个完整的例子:

class Something extends Controller 
{
    public function index ()
    {
    $view = new view('templatefile');
    $view->assign('variablename', 'variable content');
    }
}

在您的视图文件中:

<?php echo $variablename; ?>

这篇关于用PHP渲染视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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