user1735921
user1735921

Reputation: 1379

cakePHP - function which can be called after any controller action executes

I need a function which can be called after any controller method executes.

Forexample, beforeFilter() in App controller is always called before any controller action is executed, similarly I need something like afterFilter().

The problem with afterFilter() is that is executing before the controller action.

I have a controller name TestController and an action test(), with the following code:

TestController.php

function test() {
    echo 'test';exit;
}

And inside afterFilter() I put this code:

AppController.php

function afterFilter() {
    echo 'afterfilter';exit;
}

then only afterFilter() executes.

On commenting the above line, as follows:

function afterFilter() {
    //echo 'afterfilter';exit;
}

TestController:test() executes. So afterFilter() is getting called before the controller method. I need a function which is called after it, irrespective of the controller name or action name.

Upvotes: 0

Views: 1291

Answers (3)

user1735921
user1735921

Reputation: 1379

I found register_shutdown_function() in php. That does the trick.

Upvotes: 0

Inigo Flores
Inigo Flores

Reputation: 4469

According to the docs:

Controller::afterFilter()

Called after every controller action, and after rendering is complete. This is the last controller method to run.

Your AppController::afterFilter() callback is working as expected. You might think it's being called before TestController::test() because you are not able to see any output on your browser.

Try this:

function afterFilter() {
    echo 'afterfilter';
    echo $this->response;
    exit();
}

Upvotes: 2

DIDoS
DIDoS

Reputation: 822

I think what you are searching for are dispatch filters.

Upvotes: 0

Related Questions