简体   繁体   中英

How can i use a controller's method in every web page of the application in cake php 3

I am using AdminLTE theme now i want to add a functionality in header in which i need data from database how can i get this done in cake php 3 . I have done it by calling query and getting data in view but that is violation of mvc. How can i get data from database and use this data in every view.

I think You can use Cake's Controller event beforeRender() inside AppController . Using this functionality, You can simply output data for every method in controllers which extends AppController . I use it quite often for this kind of functionalities.

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

Then in your templates You have access to $notifications variable

<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>

To make it more common you can make an element of header and footer. And please don't ever call query and get data in view. You can get data in your controller's respective method and set data in view(also in element).

For how to create element please visit https://book.cakephp.org/3.0/en/views.html#using-view-blocks .

And I recommend to complete this tutorial to get more in-depth idea of CakePHP https://book.cakephp.org/3.0/en/tutorials-and-examples/cms/installation.html

Please comment if you like to know more or have any query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM