Call component method on all controllers in CakePHP 3

0

I would like to know how to call a method of a component that I created in CakePHP 3 on all controllers, as well as Auth that checks whether the user is logged in or not on all controllers. However I also want to be able to call another method of this my component on some controllers in beforeFilter before it executes the default method that will always be executed.

Example:

In some controllers in beforeFilter I allow some actions of it with $this->Auth->allow('add') and so when AuthComponent will check whether the User is logged in or not he ignores because the page was set as allowed, I need to do basically the same with the component I created.

I want to perform a certain default action on all controllers, but I can set some settings on the beforeFilter of any controller before the default action is performed.

    
asked by anonymous 11.06.2017 / 14:42

1 answer

0

I'll leave here how I solved my problem / dilemma, in case someone needs to do the same thing as me.

As part of the AppController, I called the method I created from my custom Component so that it runs on all pages as follows:

public function beforeFilter(Event $event)
{
    //some code here...
    $this->MeuComponent->metodoPadrao();
}

Then on any specific Controller where I want some other method to be executed before beforeFilter() , I call this method on metodoPadrao() of Controller as follows:

public function beforeFilter(Event $event)
{
    $this->MeuComponent->metodoEspecifico();
    parent::beforeFilter($event);
    //some code here...
}

So CakePHP executes beforeFilter() before exiting metodoEspecifico() , in Controllers where it is "called" before metodoPadrao() .

    
12.09.2017 / 19:26