How to Implement MVC from Scratch in PHP

How to implement MVC from scratch in PHP?

Your question somewhat smells like Not-Invented-Here-Syndrome. In this case, my advice would be to live with the extra baggage of existing frameworks when you can be sure they are thoroughly tested and supported. Don't reinvent the wheel.

On the other hand, the above argumentation would prevent new frameworks to be written. And writing one from scratch is a good coding exercise to learn and understand the MVC pattern.

So if you are really determined to do it, my suggestion is to learn what each part of MVC is, does and how they interact. You will inevitably come across the FrontController pattern as well, so you will want to learn about this one too.

Note that you are not the only person wanting to do this:

  • http://www.google.de/search?q=front+controller+php
  • http://www.google.de/search?q=build+your+own+mvc+php

And there is also this interesting article by Rasmus Lerdorf

  • http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html

Designing/Implementing MVC from Scratch

There are plenty of frameworks to help you with this. I would recommend using CakePHP, http://www.cakephp.org. It has good documentation, a large community and a lot of tutorials!

PHP MVC from the scratch - How to connect these classes?

Since I am doing the same exact thing now, here is my perspective:

  • do not use magical Bootstrapper, Core or Initializer classes. It is much better to put that functionality in something like a bootstrap.php or init.php file. In my project such file contains all the "wiring" between other classes (the instances of Router are created, different factories are injected and so on).

  • do not use global state in your application (the Register and Config would be the most likely candidates of introducing global state). I would recommend for you to watch this lecture playlist to gain some insight.

  • if answer is "singleton", you are asking the wrong question

  • where application starts, depends on how you create the code, but it should not be kicked of from inside the class. Think of other people people (that would include you, after 6 month) who might need to understand how your framework works. Digging thought another class, just to get to the magical init() function would be annoying.

  • learn what SOLID principles and Law of Demeter is.

.. my two cents

How to develop a MVC framework from scratch?

The "model" part of MVC refers to the data access layer, so you should create classes to read from/write to the database. Often it's one model per database "entity", so, say, one class for articles, one class for categories, plus a simple database class is a good idea.

The "controller" part is the general logic, and usually the entry point. Here you check the input and requested page, use the model to find the correct data and store in variables for the view.

The "view" part as you said is quite easy. Just include a file from the controller that mostly consists of HTML but outputs your PHP variables.

How to Implement MVC in PHP

1) So, please explain to me how it would be incorrect to instantiate
objects in the model.

It's not incorrect at all. The goal is thin controllers and fat models, however, so I do object creation in my controllers and let the models/services do the heavy lifting.

Caveat: It's best to do object creation somewhere else, in a bootstrap, perhaps, and use dependency injection to feed those objects to your controllers. That being said, much of my object creation happens in the controller as needed.

2) As this HTML will be passed to the view to be displayed into a DIV
using the jQuery function described above, is it okay for my
controller to have this sort of information going out?

Yes, it is. The controller will pass data from your model to the view.

MVC framework recommendations

Unless you just want to, or have to, don't roll your own MVC. Pick a framework, do a little studying, and win.

  • Slim
  • Aura
  • Symfony
  • Zend

What should we know to develop our own PHP MVC frame work (such as codeigniter)

Your answer should be:

  • An application based on MVC respects the separation of concerns principle. First separation: the UI logic from the business logic (the "M" component). The second separation (pertaining the UI logic): the user request dispatching logic (the "C" component) from the presentation logic (the "V" component).
  • The "M" component is unaware of any other application components and is implemented in such a way, that it can be shared by multiple applications (even of different types).
  • Each component can be modeled and implemented in different ways. Here can be discussed, depending on the requirements, which objects should be used and how they should interact with each other... In other words, this is the part where you would "hardly give a specific answer to the point". Below is an example presenting my chosen approach on the workflow of a web application using MVC.
  • The advantages of (developing an application using) the MVC pattern: components reusability, good testability, the possibility to easily perform changes on a certain component based on developer's specialization. Other advantages could be discovered by viewing/reading the first resources posted at the end of this answer.
  • As for the disadvantages: added complexity (I, personally, don't see any other).
  • Object-oriented programming, SOLID principles, clean architecture, clean code, design patterns, unit testing, etc.

Example of a web application implementing MVC:

Here is an overview of my chosen approach on the workflow of a web application using MVC - mainly inspired by Robert Martin's presentation Keynote: Architecture the Lost Years and trying to respect the workflow of the original MVC pattern presented by Trygve Reenskaug in 1979 (e.g. the controller updates the model, the view pulls data from it, irrespective of the controller).

You can read more details about each component in this older answer of mine.

Sample Image

Sample Image

Sample Image

Some resources:

  • Keynote: Architecture the Lost Years by Robert Martin
  • GeeCON 2014: Sandro Mancuso - Crafted Design
  • MVC, Delivery Mechanism and Domain Model
  • How should a model be structured in MVC?
  • Catalog of Patterns of Enterprise Application Architecture
  • Clean Code III: Functions - Robert C. Martin
  • SOLID Design Principles (Code Walks)
  • Design Patterns in Object Oriented Programming

How to MVC in php without the use of some framework

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:

  1. Redirect all trafic to a central page, so that every request gets
    handled correctly.
  2. Extract the controller and action from the request url. (for example, a request to http://yoursite.com/Task/Add, you have to translate that to the Add method on the TaskController)
  3. Load the controller class (in our example TaskController). Perhaps using Autoload.
  4. Call the Add method on the Controller
  5. Show the result

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.

Getting started with PHP / MVC

I would suggest you look at the MVC Design Pattern so that you understand it before you start using it.

Ideally, you should already have made some projects where you suffered a little bit because you wanted to change stuff when your project was at least halfway done.(This is one of the main motivators behind a lot of so-called advanced programming techniques. Ease of modification, flexibility and so on).

This is where stuff like what you mentioned (OO,MVC, and I would add TDD, Design Patterns) all come in).

What I do for myself and suggest others do is the following. Look into whatever you want, be it TDD, MVC or any other advanced technique. But wait until you need them.

In my personal opinion, one can much better appreciate the value of OO and MVC when one has gone through a naïve project and suffered from lack of functionality these techniques provide...

The golden rule is.. only start using a new technique when you've understood it and seen what benefits it can bring.

I say that because what I see in real life is that many people use stuff like OO, MVC and even Design Patterns without understanding the why's behind. I don't think that helps at all.

Good luck.

Getting started with PHP / MVC

I would suggest you look at the MVC Design Pattern so that you understand it before you start using it.

Ideally, you should already have made some projects where you suffered a little bit because you wanted to change stuff when your project was at least halfway done.(This is one of the main motivators behind a lot of so-called advanced programming techniques. Ease of modification, flexibility and so on).

This is where stuff like what you mentioned (OO,MVC, and I would add TDD, Design Patterns) all come in).

What I do for myself and suggest others do is the following. Look into whatever you want, be it TDD, MVC or any other advanced technique. But wait until you need them.

In my personal opinion, one can much better appreciate the value of OO and MVC when one has gone through a naïve project and suffered from lack of functionality these techniques provide...

The golden rule is.. only start using a new technique when you've understood it and seen what benefits it can bring.

I say that because what I see in real life is that many people use stuff like OO, MVC and even Design Patterns without understanding the why's behind. I don't think that helps at all.

Good luck.



Related Topics



Leave a reply



Submit