【问题标题】:CakePHP: Element or HelperCakePHP:元素或助手
【发布时间】:2013-01-12 18:39:01
【问题描述】:

我正在使用 CakePHP (2.2.x) 构建博客,博客的一部分是侧边栏。像 wordpress 这样的侧边栏,其中包含最近的帖子、档案和元数据。我不确定是否应该为侧边栏使用元素或助手。

目前我正在使用一个元素。部分代码sn-ps:

控制器/PostsController.php

public function index() {
    $this->set('posts', $this->Post->find('all'));
}

public function show($id) {
    $this->set('posts', $this->Post->find('all'));
    $this->set('post', $this->Post->findById($id));
}

查看/帖子/index.ctp

<div class="span8">
    <?php foreach ($posts as $post) { ... } ?>
</div>
<?php echo $this->element('sidebar', array('posts' => $posts)); ?>

查看/帖子/show.ctp

<div class="post">
   ... render the post using $post ...
</div>
<?php echo $this->element('sidebar', array('posts' => $posts)); ?>

视图/元素/sidebar.ctp

<?php foreach ($posts as $post) { ... render the recent posts ... } ?>

如您所见,show.ctpindex.ctp 都包含 sidebar.ctp 元素并且都需要 $posts 变量。所以我需要在indexshow 操作中调用$this-&gt;Post-&gt;find('all')。 我想打电话给$this-&gt;Post-&gt;find('all')一次,我想知道使用 Helpers 是否有帮助。

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    你会想要使用requestAction():

    您可以通过使用 requestAction() 来充分利用元素。这 requestAction() 函数从控制器获取视图变量 操作并将它们作为数组返回。这使您的元素能够 以真正的 MVC 风格执行。创建一个控制器动作来准备 元素的视图变量,然后在里面调用 requestAction() element() 的第二个参数为元素提供视图 来自控制器的变量。

    您可以在此处阅读有关它们的更多信息:http://book.cakephp.org/2.0/en/views.html#passing-variables-into-an-element

    基本上,您只需指定您希望元素在何处检索其数据。当元素加载时(无论在哪个页面上),它将运行指定的操作来检索您希望它拥有的任何数据。

    【讨论】:

    • 是的,这很合适。谢谢。
    • 请注意 requestAction 很慢。这是一个完整的请求,至少在 v2.x 中是这样。
    猜你喜欢
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多