tags:

views:

3277

answers:

7

I'm trying to learn more about MVC but I would really like some examples I can play with and modify to help learn the concepts and my language of choice is PHP.

Books/websites are preferred, thanks!

EDIT: I didn't really want to use a framework...

A: 

I guess you may find the CakePHP framework which implements the MVC design pattern useful, check this site http://cakephp.org/

Ahmad
Hrmmm...I'm just having to learn PHP for a project where I've basically been tasked to modify a cake app. It seems like an MVC implementation to me? Maybe a bad one at that but I don't see why it wouldn't be a decent framework to start leaning? Not sure why this Answer had a down vote.
matt_dev
Doh!...sorry. Didn't see your comment about NOT wanting to use a framework. Cake is a web applicationframework (for anyone who's interested). It also includes an MVC to drive it's user interface.
matt_dev
+2  A: 

The web is full with articles on this subject.

For example Understanding MVC in PHP

grigy
+2  A: 

The Zend Framework documentation has a quick explanation of MVC and a walkthrough of setting it up using the Zend Framework library.

Eran Galperin
A: 

I use and recommend CodeIgniter.

Toby Hede
A: 

No one has said it yet ....

I like symfony

benlumley
+9  A: 

Questions about MVC spread everywhere around, and I found myself difficult to learn what it was about. I guess I am going to write a quick introduction because I really think it's easy to understand if you have the right informations at your disposal.

What do you need to know to understand MVC

Before trying to understande MVC, you must understand fully the difference between :

  • the data;
  • the way you represent the data;
  • the data processing.

The data is you information in its purest form. It's the input of your program. Most of the time the data is what is stored in files or a data base but in can be user input as well. (1)

The way you represent your data is how you decide to show the data to the external word : it can be HTML, pure text, XML, JSON or whatever.

The data processing is all the magic stuff you do with your code to manipulate the data between the moment when you take it from the source, to when you transform it to its representation. Deciding what to do if a user is logged in or grouping all the results of a user_search in one var is data processing.

What is MVC and why / when do you want to use it ?

MVC is a design pattern. It means it's a generical solution that smart guys invented to solve a programming problem that you encounter really often. It works with any technologie, it's just a way to program you app.

MVC stands for Model, View, Controler. It aims to separate your app in this 3 components :

  • The Model : this is your data (and some code to easily manipulate it).
  • The View : this is the way you represent you data.
  • The Controler : this is the data processing, the glue between the Model and the View.

It's a very nice way to build wae apps because it's clear and easy to maintain. It allows you to reuse a lot of code (your use of model code is shared across different views) or to change your input source (if your data base change, only your model change, the rest of your app works the same !) and your formatting format (same data for a Web page and a RSS stream...).

Designers can work on the views without needing to know how your app is built.

AJAX apps fit better because their are few dependencies between you app components.

A very basic MVC example (WARNING - PHP Inside)

I am a Pythonista but I am going to use PHP for this one, as it is a typical question that comes back among PHP rookies.

Let's picture a web site where you can get VOD :

Example of Model files :

Here you put Pure PHP (methods call some SQL code (2)). This files do nothing themself, they are your library describing the data and coding behavior.

User.class.php

<?php

class User
{
    function getUserName() {}

    function isLogged() {}

    function logIn(username, password) {}
}

?>

movie.class.php

<?php

class Movie
{

    function getTitle() {}

    function getPrice() {}

    function loadBy(title, price=5) {}
}

?>

Example of View files :

Here you put formatting code (in Web site, it's mostly HTML) and VERY FEW PHP code. The PHP code is just here to access the data exposed by the Model. This files do nothing themself, they are your templates showing how to display the data to your clients.

logged.php

<p>You are now logged as <?php echo $user->getUserName() ?></p>

<p> You will be redirected to the home page in seconds...</p>

*movie_search_result.php*

<h1>The following movies match your criterias :</p>

<ul>
<?php foreach ($movies_list as $movie):  ?>

 <li><?php echo $movie->getTitle().' ($'.$movie->getPrice().')';</li>

<?php endforeach; /* we use the alernative PHP syntax here, it's suitable for Views*/ ?>
</ul>

Example of Controler files :

Tis is the hardest part to understand. Beginers (me first) can't imagine what to put in the controler :-) Well, it's pure PHP code that check what the user want, then fills variables with data from the Model and pass it to the View to finally serve the view to the user.

search.php (3)

<?php

require 'model/Movie.class.php';

if (isset($_POST['subject'])
{
  $title = $_POST['subject'];

  $movies = Movie();
  $movies->loadBy($title);

  require 'view/movie_search_result.php'

}
else
{  
  require 'view/movie_search_form.php'
}

?>

index.php

<?php

require 'model/User.class.php';

$user = User();

if ($user->isLogged())
{
  switch ($_GET['action'])
  {
      case 'search' :
          require 'search.php';
          break;
      case 'logged' :
          require 'view/search.php';
          break;
     [...] 
  }
}
else
{
   require 'view/login.php';
}

?>

How can you self learn MVC

Well, there is no other way that using it.

So when you start coding a new app, do it using your own hand coded MVC (as simply as possible, as explained here : http://stackoverflow.com/questions/113077/keeping-my-php-pretty#113851). Your only objective, as a beginer, is to separate fully the 3 components. Don't think about optimization, just do it.

At first, you'll do it the wrong way (the code above is horrible), but make it works. You'll understand better the principle, and your app won't be worst anyway since you used probably a bad architecture before.

What to do next ?

Once you have understood the principle, you can start using tools to make it right :

  • MVC frameworks like ROR, Symfony or Django improve your productivity while helping you to create a robust (and above all secure) code for the Controler (and more).

  • ORMs automatize the way you build the Model, saving you time and improving perfs.

  • Templating systems give you the most of the concept of the View.

BTW, moderns frameworks usually ship with an ORM and a templating system.

Good coding !

(1) I know that files and data base are actually data representations too and that data is only a virtual concept that only can be manipulated trough representations, but please, don't scare the noobs :-)

(2) Yes, they are ORM. Too complexe to introduce it here.

(3) I know you should sanitize the data, do usual checks, etc. I don't want to overload the example.

e-satis
+1  A: 

Like you, I also didn't know anything about MVC until I came across the well written User Guide of Codeigniter. I recommend that you, at least, have a look through these pages:

Even if you don't end up using this brilliant framework, these pages linked will help you tremendously in understanding MVC, in an easier way than any of us who aren't professional writers can teach you.

Click Upvote