Welcome Guest, Not a member yet? Register   Sign In
problem with custom controller constructor
#8

(06-22-2022, 12:54 PM)groovebird Wrote:
(05-29-2021, 12:25 PM)includebeer Wrote: Don't use a constructor. Override initController(), don't forget to call parent::initController(), and then do what you need to do.
But, a better approach, would be to create a filter and do your redirect in it.

Is this the CI4 Way to use a constructor? I had the problem to access the request object in the constructor and got another solution here in the forum. You can call the request class with a service in the __construct method. I don't know if there are problems if the request class is called again in the initController method.

No, it's not the CI4 way to use a constructor. The problem is you're trying to access objects that are not yet initialized. The request object is available after initController() has run. The constructor is too early in the cycle. Look at the code in the BaseController for an example. You need to override the initController method, call its parent, then do what you want after that.
PHP Code:
    /**
    * Constructor.
    */
    public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request$response$logger);

        // Preload any models, libraries, etc, here.

        // E.g.: $this->session = \Config\Services::session();
    
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply


Messages In This Thread
RE: problem with custom controller constructor - by includebeer - 06-22-2022, 02:12 PM



Theme © iAndrew 2016 - Forum software by © MyBB