We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Checking auth in controller's initialize() method.

Let's suppose that we have this kind of API controller. In initialize() action we're checking if allow access to action or no.

class ApiController extends Base_PublicController
{

    const CODE_ERROR_AUTH = 1; //ошибка авторизации

    const API_KEY = 'some_api_key'; //do not modify!

    public function initialize() {
        $this->view->disable();
        if ($this->request->getQuery('key') != self::API_KEY) {
            $this->response->setContentType('application/json');
            $data = array(
                'status' => 'error',
                'code'   => self::CODE_ERROR_AUTH,
                'error'  => 'Unauthorized request',
            );
            $this->response->setContent(json_encode($data));
            $this->response->send();
        }
    }

    public function indexAction() {
        echo 'executing index action';
    }

}

When I'm trying to access domain.com/api/index/ I'm still getting indexAction() executed. How to prevent futher executing of controller's methods after $this->response->send(); Using "exit" after $this->response->send() is not OK for me.

Or maybe it is not a good practice at all doing so?

Thank you!

I'd use the beforeExecuteRoute event in combination with the dispatcher. Check out this chapter in the docs to get an idea: https://docs.phalcon.io/en/latest/reference/tutorial-invo.html#securing-the-backend