0

Okay, there are some (possible a lot) concepts of Routing/Controller/View that I have difficulties with.

I use https://github.com/mrjgreen/phroute as router and creates a route like this:

$router->get([‘/users/view/{id}', 'viewUser’], ['controllers\UserController','view'])

Now in the UserController view function I have the $id available and pass that along to the view. In the controller and in the view I need access to other objects as well. Should I create those objects at router level and pass them along to the controller, should I create those objects at controller level and pass them along to the view or should I do something completely different? I guess the use of global vars is a no-go.

I need those objects in a lot of controllers and creating them in the router seems like a way to initiate them just once instead of repeating it in every controller.

This seems to work just fine but it doesn’t seem quite right

$objects_I_need = [
    'object1' => new Object,
    'object2' => new Object
];

$router->get(['/users/view/{id}', 'viewUser'], function ($id) use ($object_I_need)
{
    return (new Controller\UserController()->view($id, $objects_I_need);
});

Perhaps a Factory as described here is the way to go?

Thanks in advance for inputs

Community
  • 1
  • 1
sjosen
  • 551
  • 1
  • 6
  • 10
  • The router is responsible just for handling the request and passing it to a controller. It should not tell the controller or the view what objects/data to have/use. If you need some data in the view it should definitely be prepared in the controller and passed to the view from there. But if you need the same data in many views you should not repeat yourself and create the same objects in all the controllers. – thefallen May 31 '16 at 12:36
  • There is no single solution, especially if you are rolling your own package rather than using a framework. However a simple solution would be to create an abstract base controller that all your other controllers extend. Create all your 'global' dependencies there. – Steve May 31 '16 at 12:37
  • Thanks for your input. Much appreciated. A base controller seems logical. I'm preparing myself for a switch to Laravel in the future, but it's not possible at the moment and thats why I "need" a clean and simple solution for now. – sjosen May 31 '16 at 12:46

0 Answers0