I have some (basic perhaps) knowledge of the Model-View-Controller pattern and I want to create a site using this. But I find it a bit confusing how to actually implement this. I get stuck in the details.
Say that I have a site where each user keeps some todo lists. How would you approach this? What classes would you create? Which class would output the HTML, which class would server as the controller and how would it communicate with the view to produce the output? etc.
Sorry if it seems silly and I guess it must be somewhat easy but I am stuck.
For the record:
It is not as hard to do a MVC in PHP, its more related with to be disciplined rather to be a difficulty task.
a) Model(s) (optional, you can use an array in PHP)
<?php
class MyModel() {
}
?>
b) Route (index.php?)
<?php
include "...";
// here we collects all the information, such post,get and path values
$action=...;
$param=....;
switch($controller) {
case "my": // www.myweb.com/my/action
include "controller\MyController.php"; // open the right controller.
break;
}
?>
c) Controller
<?php
include "model\MyModel.php";
switch($action) {
case "add":
// here live the logic, information, call for services and such.
$model=....;
// and finally...
include "view\MyView.php";
break;
}
?>
d) View
<html>
<body>
<?=$model->field;?>
</body>
<html>
As a note:
a) The view should be clean as possible. Think that the view could be created by a web designer that doesn't care about php.
b) The view is always the last step of the process. The view web always returns nothing.
It is very possible to do this without an existing framework, and just create your own. Its not a very difficult task anyway.
Not being application-specific, your MVC framework would have to do the following:
There are multiple ways to implement views, you could emulate ASPMVC and have each Controller's action return an ActionResult
, which has one method Execute. Then an overload of that, ViewResult
would take care of loading the correct view and including it with the proper ModelData
.
Here's the precise answer to your question from RASMUS LERDORF himself. Read through.
Read the following intro to Symphony network: http://symfony.com/doc/current/book/from_flat_php_to_symfony2.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With