如何在cake php 3中的应用程序的每个网页中使用控制器的方法

时间:2017-10-27 11:58:09

标签: cakephp cakephp-3.0 adminlte

我现在正在使用AdminLTE主题我想在标题中添加一个功能,我需要数据库中的数据如何在蛋糕php 3中完成此操作。我通过调用查询并在视图中获取数据来完成它,但这违反了mvc。如何从数据库中获取数据并在每个视图中使用此数据。

2 个答案:

答案 0 :(得分:0)

我认为你可以在beforeRender()内使用Cake的Controller事件AppController。使用此功能,您可以简单地为扩展AppController的控制器中的每个方法输出数据。我经常使用它来实现这种功能。

<?php

// src\Controller\AppController.php
namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;

class AppController extends Controller
{
    /**
     * Before render callback.
     *
     * @param \Cake\Event\Event $event The beforeRender event.
     * @return \Cake\Network\Response|null|void
     */
    public function beforeRender(Event $event) {

        $this->loadModel('Notifications');
        $notifications = $this->Notifications->find('all' , [
                'conditions' => [
                    // get notifications for current user or default demo notification 
                    'user_id' => $this->Auth ? $this->Auth->user('id') : 0
                ]
            ])
        ->toArray();

        $this->set(compact('notifications'));
    }    
}

然后在您的模板中,您可以访问$notifications变量

<div class="list-group">
    <?php if(count($notifications)):foreach($notifications as $item): ?>
        <div class="list-group-item">
            <?= h($item->content) ?>
        </div>
    <?php endforeach;endif; ?>
</div>

答案 1 :(得分:0)

为了使它更常见,你可以创建页眉和页脚元素。请不要调用查询并获取数据。您可以在控制器的相应方法中获取数据,并在视图中设置数据(也在元素中)。

有关如何创建元素,请访问https://book.cakephp.org/3.0/en/views.html#using-view-blocks

我建议完成本教程以更深入地了解CakePHP https://book.cakephp.org/3.0/en/tutorials-and-examples/cms/installation.html

如果您想了解更多或有任何疑问,请发表评论。