phpcodeigniter-4

How do I know which controller is currently running in the BaseController?


I want to check that a user is logged into my app directly in the initController method of the BaseController and redirect them to an OIDC authentication mechanism (AuthController) if not logged in.

If I run the following code, my script obviously loops to itself.

BaseController.php

public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);

        if (!session()->userLogin) {
            //no user logged in
            $this->response->redirect(site_url('/auth'));
        }
    }

So, how can I prevent AuthController redirecting to itself?

Should I override the initController method in AuthController or can I check the name of the current controller or route in the initController of BaseController with get_class($this); ?

Which is the most appropriate?


Solution

  • The simpliest way to do it, like sayd by @simonweber, is to use the global filters, with an EXCEPT directive.

    It has been anwswered already here :

    how to excluding global filter for a single controller