CodeIgniter Forums
Access $request in __construct in ResourceController? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Access $request in __construct in ResourceController? (/showthread.php?tid=78229)



Access $request in __construct in ResourceController? - blaasvaer - 12-17-2020

How do I access the $request in the __construct of a ResourceController?

I've tried:
Code:
$data = $request->getRawInput(); // Crashes with Internal Server Error

$data = $request->getVar('some_var); // Crashes with Internal Server Error



RE: Access $request in __construct in ResourceController? - paulbalandan - 12-17-2020

If I'm not mistaken, ResourceController and ResourcePresenter both extend CodeIgniter/Controller. So the request object is not accessible in the __construct but on the initController method.

In your class extension of the ResourceController, for example ApiController, you would have something like this:
PHP Code:
public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger)
{
    
parent::initController($request$response$logger);

    
$data $this->request->getRawInput();

    
// If you want $data to be accessible in other places of the class, you might want to set it as a property instead. Then set it like:
    
$this->data $this->request->getRawInput();




RE: Access $request in __construct in ResourceController? - blaasvaer - 12-17-2020

Yes, that's why I hate that the CI team 'broke' __construct. We've all grown used to being able to use it like we expect to. And now, all of a sudden we have to 'adapt' to these weird custom approaches ... it's NOT good.

If I add your code ... my ResourceController just breaks!

WHAT am I supposed to be doing with it?

And WHY do I have to 'extend' a Controller in order to have access to the $request? It doesn't make ANY sense to me, at all!

Had to add this: public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)

But it still seems annoying and cumbersome to have to make all this basic stuff ... in order to access the request ... now when would a Controller NOT have a request? I cannot see the case for leaving this out.