Is this going to help understanding MVC?

I am looking at the contents of Matt Zandstra’s book ‘PHP Objects, Patterns, and Practice’, with a view to buying it as I would like to understand MVC, but there appears to be no mention of it to my untrained eye - all kinds of patterns are mentioned:

singleton
factory method
abstract factory
composite
decorator
facade
interpreter
strategy
observer
visitor
command

and then in a later ‘Enterprise’ patterns chapters there is mention of presentation layer and business logic layer - maybe that’s it?

Will this book help me to understand MVC? With a name like that, I’m sure it must?

i think using codeigniter or cakephp first helps to understand and implement MVC

I love the “You aren’t gonna need it” link. Very good. Thanks.

Problem solved: Here in Wild East we must use a proxy from more advanced country :frowning:
Admin can safely delete this post.

All I can say is: works for me. Perhaps the site was down temporarily?

Quite an old article, been posted here many times before. The one that taught me the exact mistakes i was making :slight_smile:

Hello TomB,

first link returns empty page (FF, IE), do you see some content on it? Homepage http://blog.astrumfutura.com/ is also empty.

On that note, after reading how “MVC” is done in most “MVC” php frameworks. One you have a basic understanding of the concepts, it’s definitely worth a read of The M in MVC: Why Models are Misunderstood and Unappreciated to see where these generally go wrong.

Most “MVC” frameworks are actually “N-Tier”. Unfortunately most PHP related MVC tutorials/articles teach this too. There is a good (imho) explanation of MVC here: http://www.phpwact.org/pattern/model_view_controller which contains some vital points a lot miss.

I agree with sunwukung, you might want to start out with something a little lighter if you’ve never used MVC before. The Design Pattern book I’d suggest is the Head First, very well written, very clear, a splash of good-geeky humor, and lots of happy buyers/reviewers on Amazon. http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124/ref=wl_it_dp_o?ie=UTF8&coliid=I1OAMKDF6PUK5X&colid=1INX8C29WI78G

Also, here’s my 5 cent explanation of MVC, because it’s confusing enough that EVERYONE asks this question at some point in their careers.

MVC is a style of application design that really makes an excellent kind of sense. It’s “kinda” similar to the idea of breaking your application up into layers as in the n-tier development school. When you click on a link and request a webpage from the server, the server first hands your HTTP request to the controller, the C. The controller is the big boss and tells everyone what to do. That’s one of the reasons MVC is such a killer pattern, it’s an extension of the idea of separation of concerns which governs how to use XHTML/CSS/JS properly. If the program is not behaving the way you want (whether you’re coding, testing, or maintaining) you start looking in the controller code because that’s where the problem is going to be. The controller code is roughly equivalent to the Application Logic layer.

The controller is going to create output, usually this is XHTML. This is what builds the output that you’re actually going to see from the HTTP response (hence View, the V). The view includes all the XHTML sent, but it also includes all classes responsible for creating that code. Note this is different from the classes that CHOOSE which classes are permitted to create code. The code that writes XHTML is the View, the code that chooses which View classes get called is the Controller. The View is roughly equivalent to the UI layer.

Except in the most simple of application pages (ie static pages with fixed XHTML) your pages are going to be dynamic. They are going to depend on input from the user. They are going to depend on data stored in a database or an external web service. Whatever. You need information that is not static, this data is the Model, the M. Database data is probably the most common model for most websites, but any information you draw in from the user also counts. I’m not sure if anyone else would agree with me, but I prefer to think of the Model not just as the physical database, but also the code which handles the actual implementation of getting a hold of that data. Therefore, I think of the Model as being part data and part Data Access Layer which handles the grubby details of getting that data for the controller.

The advantage of including the code along with the physical database is that your controller then really does nothing except make choices. Again, this is excellent abstraction and separation of concerns for the inside of the application. If your data is incorrect, go check the Model; either the data from the database is bad or the DAL code is not getting the correct data for the controller to act on. If your output is incorrect (granted there could be controller problems) you start by looking at the View. Is the XHTML miscoded, either miswritten or the View code responsible for putting the pieces together? And if your program is not behaving itself (including incorrect output when you can’t find a problem in the View), you check out the controller. All it does is look at the user input (including all portions of the HTTP request) assemble whatever extra data it needs from the model and then issues data and commands to the View which constructs the output.

Doh! No, I meant this one - thanks!

http://www.wrox.com/WileyCDA/WroxTitle/Professional-PHP-Design-Patterns.productCd-0470496703.html

No. All those things can be used in conjunction with MVC but are not part of, or required by the MVC architecture.

With regards to the book content, the sections pertaining to Front Controller, Command and Page Controller. are relevant to MVC architecture, but they are not explicitly titled MVC.

It’s a great book, but it’s a little hard to digest. I recommend this book for a more lightweight introduction to OOP & Design Patterns.

I’d recommend both - but you might need some time away from the screen with the first to really digest some of the material - it’s very dense.

Thanks for the replies.

Sunwunkung, did you mean to refer to a second book when you said “this book”?

I am not a fan of Zend Framework either. Personal tastes and the fact that I code with CodeIgniter as my framework. It is far easier to get a CI site up and running than the Zend system, where there are plenty of config files to meddle with.

The MVC system in CI tends to be more straight forward.

The downfall of CI is that it still retains a lot of php 4 at its core so you cannot really expect to get down and dirty with interfaces. If you have a php 5 stack you can utilize abstract classes pretty well in CI 1.7.2 and 2.0beta. If you need a more rubust php5.3 stack then you should use Kohana 3. Kohana v1 and v2 are based off of CI. 3.0 is a complete rewrite and takes advantage of php 5.

CI is very easy to setup and use. It doesn’t force you to use MVC and lets you get working systems with minimal MVC tech. However, as you grow as a MVC developer you will find that CI can be very, very MVC savvy and you’ll want to take advantage of it. Also, you’ll come to find that writing in php 5 can make MVC apps wonderfully easy to manage.

For instance, if you wanted to write a driver for importing data from csv files, or xml files etc you can write an abstract class that has all the methods without implementations… or some that will always be the same despite the type of child class so they will be implemented in the class. Then you just need to extend it and implement the system yourself. The app will be clean, easy to manage etc.

Also, another thing about MVC and OOP…

Extending Controllers by making a base controller ( and you can do the same with models ).

So for example in CI when you extend a core library you have to prefix it with MY_

Thus, MY_Controller.php would be in your library directory for the appliation:


class MY_Controller extends Controller {
    
    public function __construct()
    {
        parent::Controller();

    }
}

Then you can then make a Public_Controller that extends MY_Controller and an Admin_Controller that also extends MY_Controller. In MY_Controller you might want to initialize some session information for all users. Then in the Admin_Controller you can tighten up with security checks and route them to an admin field.

Not that you cannot do this in Zend… but I find it easier to implement in CI. The good things about Zend is that there are a lot of core libraries built for interacting with web services. These usually are 3rd party with CodeIgniter and you can find tons of 3rd party libs on bitbucket or github.

There are already mongoDB libraries, authorize.net libs, paypal etc etc for CI ready to be tapped. Also modular separation libraries so you can build apps more modularly ( which I find a god send ).

/application
-config
-controllers
-helpers
-library
-models
-views

If you did modular separation, once you install the few files from the library where they need to go, you’d add a directory called modules to the app directory then you can mirror those above in a new directory in the modules directory. So if you want to create an accounting module

/application
-modules
–accounting
—config
—controllers
—libraries
—models
—views

your controller needs to be named accounting.php in the controllers directory of your module… but you can do local module routing in a routes.php file in your —config folder that can route accounting/new controller method when what you are really asking for is a second controller’s method that is in the same directory of —controllers.

example:


<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| 	example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
|	http://codeigniter.com/user_guide/general/routing.html
|
*/

$route['accounting/payment(:any)?'] = "gateway/start$1";

/* End of file routes.php */
/* Location: ./system/application/modules/accounting/config/routes.php */

So when you call http://www.yoursite.com/accounting/payment/5

The module’s route is passing off the payment method of the URL to another controller in the directory with the accounting controller with a uri segment ( say a payment ID ) with 5.

Very, Very good way to build your apps.

Anyways… the real crux of MVC learning is to understand what you are doing with the URL routing and how it maps to your application files. Then start tinkering with the libraries in the controller, then break down things to keep it DRY ( Don’t Repeat Yourself ). This can take weeks to years to really grasp it, so just start doing it!

Because it’s like having your teeth pulled out for 8 hours a day :lol:

OFF TOPIC

Curious. Why?

To address the OPs point, I spent a long time trying to fathom the benefits of MVC too, before during and after intense swotting and playing with patterns.

While I used CI on a couple of projects and got along with it fine, I still could not fully understand the overarching benefits (Why am I doing it this way?).

I finally got that “light bulb moment” when I read a book half of which is meant to be read like a novel, and half of which is a patterns reference supporting the narrative in the first half.

The book is Fowlers Patterns Of Enterprise Application Architecture [POEAA], where he lucidly and carefully explains the need for layers of software, and explores the interactions between various levels. Naturally MVC is covered.

The book is very cleverly laid out.

The code samples shown are mostly in Java and C# - not in PHP - but I finally understood what MVC was about because for me Martin Fowler spoke with a high degree of lucidity and in a language and tone that appealed to me.

I am not saying you have to agree with everything he writes, nor that everything will be relevant to you or the situations you find yourself in, I am just sharing what worked for me.

Hey,

I have that book (Objects, Patterns, and Practice) and I recommend getting it! It does have a large chunk on MVC patterns in the Enterprise Pattern area. I go through different areas every few days, It’s a very rich book that is worth your time, after-all there is more than just MVC :slight_smile: I wouldn’t suggest getting this book if you only want the MVC content, there are probably better books for this.

I also have a book called Practical Web 2.0 Applications with PHP, this book is decent if you are interested in the Zend Framework. The more I use ZF, the less I enjoy it. Anyways, It is a huge tutorial book to create a Blog application from start to finish, but it feels like it’s too tailored of a system (How the author likes to do things) and doesn’t stick to the ZF directory structure. It’s a great book but it actually confused me more about ZF in the beginning.

Well the main benefits from MVC are reusability and scalability. This is achieved by splitting everything up into relevant small tasks (Which is actually a OOP concept rather than an MVC one, MVC just enforces it by categorising the objects), inevitably this creates a situation where a “page” is accessing a lot of different functions in different places. In theory, it should be easier to track down (E.g. your query should be in the model layer, meaning you don’t need to look through any display logic to find it). Of course in reality it’s not always this simple.

Without separating these things out you end up with repeated code which is a much larger issue from a maintainability point of view-- all changes to the system have to be located and updated in multiple places. On larger projects this could be a huge number of locations, some of which not immediately obvious.

As with anything, it’s a trade-off, but one I believe to be very worthwhile.

It was an hour spent following the code through trying to find where a particular query was defined. And probably not no. It was made worse as the problem was with a query that was getting generated within their framework from several places. Hence why I couldn’t do a plain simple search lol. The actual product in question was oscommerce though I’m not sure if anyone else has had dealings with it but I found it to be a complete mess.

I guess I’m just an MVC sceptic. I could probably do with reading into it more but from my impressions of it thus far it seems to complicate things just for the sake of it. Why have just one index file and hundreds of folders when you could have files in their correct positions (with or without SEO urls) working off a directory of classes? I use OOP nowadays and even the Singleton design pattern usually for a generic app class but thus far I can’t see how MVC would help.

It makes finding the problem code harder because you have to follow the process through all the various files. I’ll probably get that wrox book that someone linked to and read up on it that way. Certainly won’t be using it for my current project though.

That is true for anything you don’t understand. :wink: Remember that patterns have two main goals: 1) to provide best practice solutions to problems, and 2) to provide a common (ubiquitous) language to discuss software design.

MVC gets an unusual amount of resistance because it asks programmers to restructure their applications. Programmers almost always have a confirmation bias toward the program structure they have evolved. Thus they have all the internal and historic supporting logic of their current system as a defense against MVC.

Buy and read the PoEAA. Then tell yourself “Martin Fowler knows better that I do … I’ll do things his way.” :wink: