My current implementation:
class SomeController extends AppController
{
function someaction()
{
$d['text'] = "ahoy!";
$this->render("someactionView", $d);
}
}
And in AppController
:
function render($file, $data = "")
{
require "views/" . $file . ".php";
}
And the $data
will be available in the views file. Is this a correct implementation? Are there any fallacies with this implementation?
IMO the
render()
method belongs to the view and not to the controller. The code should look like this:Controller:
View Base Class:
Extend View class
Short answer: no and several.
First of all, what you have there is no a view. It's just a dumb php template. Views in MVC are instance, that contain the UI logic for the application. They pull information from model layer and, based on information they receive, create a response. This response can be simple text, JSON document, a HTML page assembled from multiple templates or simply a HTTP header.
As for controller, it's only task is to alter the state of model layer and (on rare occasions) the current view. Controllers do not initialize the views nor do the populate templates.
Basically you do implement it like the most frameworks do. There's a couple of problems with that:
require "views/" . $file . ".php";
inrender()
method - you again tighly couple it. What if you change the location of views? Then you would have to slightly rewrite your method. This approach merely kills reuse-ability.To refresh your basic knowledge:
Controller (also known as Editor)
Serves only singular purpose. It changes model state - that is, it should take an input that comes from
$_POST
,$_GET
,$_FILES
,$_COOKIE
. In controller only variable assignment should be done and nothing more.View
A view has a direct access to a model. In order to make make views more re-usable and maintainable you'd better pass required things as function parameters (or via setters)
How the view should be initialized and how the variables should be passed to it?
First of all - a view should be instantiated outside MVC-triad. Since a controller writes either to view or model - you'd pass variables to view via controller.