7

私は独自の MVC フレームワークを作成しており、ビュー レンダラーに到達しました。コントローラーの vars を View オブジェクトに設定し、.phtml スクリプトで echo $this->myvar を使用して vars にアクセスしています。

私の default.phtml では、ビュースクリプトを出力するためにメソッド $this->content() を呼び出します。

これが私が今やっている方法です。これはそれを行う適切な方法ですか?

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' ;
    }

}
4

2 に答える 2

20

単純なビュー クラスの例。あなたとデビッド・エリクソンのものに本当に似ています。

<?php

/**
 * View-specific wrapper.
 * Limits the accessible scope available to templates.
 */
class View{
    /**
     * Template being rendered.
     */
    protected $template = null;


    /**
     * Initialize a new view context.
     */
    public function __construct($template) {
        $this->template = $template;
    }

    /**
     * Safely escape/encode the provided data.
     */
    public function h($data) {
        return htmlspecialchars((string) $data, ENT_QUOTES, 'UTF-8');
    }

    /**
     * Render the template, returning it's content.
     * @param array $data Data made available to the view.
     * @return string The rendered template.
     */
    public function render(Array $data) {
        extract($data);

        ob_start();
        include( APP_PATH . DIRECTORY_SEPARATOR . $this->template);
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }
}

?>

クラスで定義された関数は、次のようにビュー内でアクセスできます。

<?php echo $this->h('Hello World'); ?>
于 2013-01-03T17:45:46.943 に答える
14

これが私がそれをした方法の例です:

<?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 関数を使用して変数を割り当て、デストラクタでその配列を抽出してビュー内のローカル変数にします。

必要に応じてこれを自由に使用してください。どのようにそれを行うことができるかについてのアイデアが得られることを願っています

完全な例は次のとおりです。

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

そしてあなたのビューファイルで:

<?php echo $variablename; ?>
于 2013-01-03T17:32:35.253 に答える