I am working on a PHP project (the code should also be readable by non PHP people though) which I am trying to setup using a true MVC structure. Or at least as closed as I can. What I am currently doing is the following:
bootstrap file
$request = new \MyApp\Services\Http\Request();
$storage = new \MyApp\Services\Storage\Session();
$token = new \MyApp\Services\Token($storage);
$user = new \MyApp\Services\User($storage);
$menu = new \MyApp\Services\Menu($token, $user);
$view = new \MyApp\Views\Index($request, $menu);
$controller = new \MyApp\Controllers\Index();
$response = $controller->frontpage($view);
echo $response;
Index controller
namespace MyApp\Controllers;
class Index
{
public function frontpage($view)
{
return $view->render();
}
}
And in my view I use the request object and the menu object to send the correct menuitems to the template(s). The request object is used to give the currently selected menuitem (of the current page) another class in the template. And I have a render()
method which simply returns the rendered HTML.
However AFAICT the above is flawed (in the sense that it hasn't much to do with an MVC structure), because:
- the controller uses a
view
instance - because of this the controller now is somewhat responsible for presentation
- the view uses the request object (which should have been the controllers task)
So what I was thinking of doing was the following:
bootstrap file
$request = new \MyApp\Services\Http\Request();
$storage = new \MyApp\Services\Storage\Session();
$token = new \MyApp\Services\Token($storage);
$user = new \MyApp\Services\User($storage);
$menu = new \MyApp\Services\Menu($token, $user);
$controller = new \MyApp\Controllers\Index($request);
$controller->frontpage($menu);
$view = new \MyApp\Views\Index($menu);
echo $view->render();
Index controller
namespace MyApp\Controllers;
class Index
{
private $request;
public function __construct($request)
{
$this->request = $request;
}
public function frontpage($menu)
{
$menu->setRequest($request);
}
}
Now the controller takes care of the request and updates the menu part of the model layer and the only thing the view has to do now is simply retrieve all the "active" menu items from the menu service.
My second code sample makes more sense to me (when talking about a true MVC structure). Is my assumption correct? Or are both case off? Anything else?
static
s everywhere it just advocates terrible practices all over the code base. – user6669 May 9 '13 at 17:37$request = new \MyApp\Services\Http\Request();
get its request data from? – PeeHaa Dec 10 '13 at 11:37