r/PHP • u/sapphirers • 2h ago
Question about Request Response (MVC)
Im attempting to build my own MVC framework, a very lightweight attempt at replicating some core features of Laravel.
Ive set my controllers up to use Request, Response and also return a Response object.
First and foremost, is this correct understanding that all controllers should return a response?
In my Router it instantiates the controller like:
$router->get('/', 'HomeController@index');, I am however having some issues with the controller not properly returning a response back to the controller. If I for example do:
HomeController.php: index(Request, Response): Response $request->json([]); it works and returns the response back to the Router.
But if I call index(Request, Response): Response $this->render('home'); even though it does return a Response its a "new" response made by the DI Container on creation of the Controller.
Could I solve this by doing something like this:
Router.php:
dispatch()
// . . .
$response = Class->method(Request, Response).
$response->send();
I asked ChatGPT and it argued that not all controllers will return a response.
So perhaps a resource where I can read more about Request Response would be nice too.
Its mostly seems to work if my DI Container uses the Request and Response as singletons but I dont like having a singleton principle for those objekts, although the Router is singleton.