原文地址:Creating Reusable Elements with requestAction
原文作者:gwoo
翻译:myleoliu

这是一个使用requestAction()创建可复用elements的简单教程. 本例提供CakePHP1.1/1.2示例代码.让我们先从一个简单的controller开始:

Controller Code:


<?php 

class PostsController extends AppController {

    var 
$name ‘Posts’;

    function index() {

        
$posts $this->Post->findAll();

        if(isset(
$this->params['requested'])) {

             return 
$posts;

        }

        
$this->set(‘posts’$posts);

    }

}

?>

首先,我们创建一个Posts controller并给它添加一个默认动作(index action),然后我们就能通过index action取得所有posts。如果requestAction()向index action发送请求,那么(index action)将直接返回posts结果集,否则(index action)就把posts发送给view。

接下来,我们来创建一个使用requestAction()的可复用element。创建文件/app/elements/posts.thtml并添加如下代码:

View Template:

$posts = $this->requestAction(’posts/index’);

foreach($posts as $post):

    echo $post['Post']['title'];

endforeach;


现在,我们可以将这个element包含进layout,view模板或者其他element中进行复用了。

View Template:

<?php echo $this->renderElement(‘posts’);?>



以上代码适用于cakephp1.1.如果你想使用CakePHP1.2,请参照下面的代码。

Controller Code:


<?php 

class PostsController extends AppController {

    var 
$name ‘Posts’;

    function index() {

        
$posts $this->paginate();

        if(isset(
$this->params['requested'])) {

             return 
$posts;

        }

        
$this->set(‘posts’$posts);

    }

}

?>

注意,我们在index action中改用了paginate()方法。在view中,我们可以设置paginate的相关参数来控制它的返回内容。

View Template:

$posts = $this->requestAction(’posts/index/sort:created/direction:desc/limit:10′);

foreach($posts as $post):

    echo $post['Post']['title'];

endforeach;


我们现在可以只返回最新的10条信息了。哇哦,我们在没有改变或创建任何action的条件下创建了一个显示最新post的element。

现在我们来调用这个element并将它缓存一个小时。创建文件/app/elements/latest_posts.ctp:

View Template:

<?php echo $this->element(‘latest_posts’, array(‘cache’=>‘+1 hour’);?>



我们仍然可以在其他View文件中使用这个element。

requestAction()方法还有很多其他的用途。但如果你想为网站创建可复用得element,那么本教程所讲述的方法是一个不错的选择。