CodeIgniter Forums
How to access request in ResourcePresenter? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How to access request in ResourcePresenter? (/showthread.php?tid=84928)



How to access request in ResourcePresenter? - rich8374 - 11-24-2022

I have created a simple ResourcePresenter, here is an example command: php spark make:controller books --restful presenter

What is the best practice way of accessing the IncomingRequest class in any of the methods?
I'm used to it being provided for me when using standard controllers which extend from BaseController.

Thanks in advance.


RE: How to access request in ResourcePresenter? - kenjis - 11-24-2022

$this->request


RE: How to access request in ResourcePresenter? - rich8374 - 11-24-2022

(11-24-2022, 05:42 AM)kenjis Wrote: $this->request

good point, $this->request does exist but I can't call $this->request->getPost() on it, whereas I can when a controller extends BaseController.

In a ResourcePresenter $this->request is of type CodeIgniter\HTTP\RequestInterface.
In a controller extending BaseController $this->request is type CodeIgniter\HTTP\IncomingRequest.

So what's the recommended way of getting a request of type CodeIgniter\HTTP\IncomingRequest into a ResourcePresenter?


RE: How to access request in ResourcePresenter? - kenjis - 11-24-2022

(11-24-2022, 05:53 AM)rich8374 Wrote: $this->request does exist but I can't call $this->request->getPost() on it, whereas I can when a controller extends BaseController.

Why not?
You can call it.


RE: How to access request in ResourcePresenter? - rich8374 - 11-25-2022

You're right, I've just tried it and I can use it fine.  I use Visual Studo Code as an editor and that was complaining that the getPost method wasn't found, I believed it without testing it.
The lesson I've learnt here is not to rely too much on the editor tools!
Thanks.


RE: How to access request in ResourcePresenter? - kenjis - 11-25-2022

@rich8374 Strictly speaking, the Visual Studo Code warning is not wrong.
In fact, there are the issues in CI4 framework code.

But anyway, the request object in the controller is always IncommingRequest if it is a web request.
So you can call its methods.


RE: How to access request in ResourcePresenter? - rich8374 - 11-25-2022

Thanks.
If anyone else is using Visual Studio Code with the PHP Intelephense extension, if you want to get rid of the 'Undefined method' problem, add the following class variable and @var tag to document the data type for Intelephense:
Code:
/** @var \CodeIgniter\HTTP\IncomingRequest $request */
protected $request;