0

我正在尝试使用 Fragment 助手类优化我的 Kohana (3.2.2) 应用程序,但我才意识到我做错了。

型号_文章:

    public function get_articles()
    {
        /*
         * This is just a PDO wrapper, I don't like the kohana built in
         * database module
         */
        $db = DB::instance();

        $article_stmt = $db->prepare("SELECT * FROM articles");
        $article_stmt->execute();
        return $article_stmt->fetchAll();
    }


控制器_文章:

    public function action_index()
    {
        $this->template->content = View::factory('welcome/index');

        $this->template->content->articles = Model::factory('article')->get_articles();
    }


风景:

        <?php if ( ! Fragment::load('home.articles')): ?>

            <!-- cache test -->

            <?php foreach($articles as $article) echo $article->title . PHP_EOL ?>

            <?php Fragment::save(); ?>
        <?php endif; ?>


您可以看到,无论视图中发生什么,查询总是被执行。我希望仅在缓存更新时执行查询。但是将模型对象传递给视图会破坏我猜的一些 MVC 约定?!有人可以告诉我怎么做吗?!

4

2 回答 2

1

缓存处理是控制器应该做的,而不是视图。

将其从视图移动到控制器并感到高兴。我没有使用 Fragment 模块,但我想您会理解要点:

public function action_index()
{
    $this->template->content = View::factory('welcome/index');
    if ( ! $articles = Fragment::load('home.articles') )
    {
        // It's better to use separate view for articles list
        $articles = View::factory('articles/list', array('articles' => Model::factory('article')->get_articles());
        // Hope not just an output can be captured but argument can also be passed to the save() method of the module
        Fragment::save($articles);
    }
    $this->template->content->articles = $articles;
}
于 2013-01-08T08:32:07.707 回答
0

您必须在视图中进行查询(如果您扩展Controller_Template了)或在控制器中回显(如果您扩展了Controller)。

例子

Controller_Article(扩展控制器):

public function action_index()
{
    if ( ! Fragment::load('home.articles')):

        $template = View::factory('my_template_view');

        $template->content = View::factory('welcome/index');
        $template->content->articles = Model::factory('article')->get_articles();

        echo $template->render();   // If you won't print anything,
                                    // don't use fragments

        Fragment::save();   // Save the OUTPUT, but DOES NOT save variables
    endif;
}

 

Controller_article(扩展 Controller_Template):

public function action_index()
{
    $this->template->content = View::factory('welcome/index');
}

查看(欢迎/索引):

<?php
    // echo $articles;     // Now Controller is not binding this variable
    if ( ! Fragment::load('home.articles')):

        // Variable - Does NOT save in Fragment
        $articles = Model::factory('article')->get_articles();

        // ECHO = save to Fragment
        foreach($articles as $article) echo $article->title . PHP_EOL;

        Fragment::save();   // Save the OUTPUT, but DOES NOT save variables
    endif;
?>

 

如果要保存变量,请使用Kohana Cache

于 2013-02-15T17:50:22.943 回答