Search code examples
cakephpcakephp-3.0adminlte

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.


Solution

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