Create your First Tiny MVC Boilerplate with PHP
videos

Create your First Tiny MVC Boilerplate with PHP

Tutorial Details
  • Topic: PHP / MVC
  • Difficulty: Intermediate
  • Estimated Completion Time: 14 Minute Video Tutorial

I’m often asked about how to create an extremely simple MVC boilerplate for small projects which don’t require a massive framework, like CodeIgniter or CakePHP. We’ll build a solution in ten minutes or so.

It’s important for me to note that I’m not advocating that you shouldn’t use large frameworks. They absolutely have their places, and I use them often. That said, there are definitely times when they can be overkill for smaller projects. When your only requirement is code organization, it’s typically better to scrape together your own MVC boilerplate.


Conclusion

If you enjoyed this video, and would like to take our tiny framework to the next level, we can definitely do so together. Let me know in the comments!

Tags: Videos
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • w1sh

    Damn you turned into an awesome programmer this past year.

  • Mark

    Great start Jeffrey,
    I’m definitely tuning in for developing this further. I’m new to mvc, and am very interested in learning more.

  • Jordan

    I too am new to MVC and would love to see this developed further.

  • Andy

    I’d love to see more of this tiny MVC. I think it’s a great way of showing how an MVC works.

    • http://jacobdubail.com Jacob

      Would definitely love to see more like this. What a great way to learn how a framework works!

      • http://sigerr.org Julien

        We would definitely appreciate new video like this one.

    • Robert

      I agree with you. Same goes for me.

  • Alex

    Hey Jeffey,

    Just like to say another great tutorial which will definitely encourage me to develop my own Tiny MVC framework. I have to say the tutorials for CodeIgniter are great as well! I would love for you to develop a mini series of TinyMVC :)

  • http://www.twitter.com/mattborja/ Matt Borja

    Here is a nice little library much similar to that used in CodeIgniter. I have this saved in application/libraries/Input.php and is included (or required) in my core.php (I use core.php instead of tinyMvc.php).

    _get);

    $this->_post = $_POST;
    }

    function get($var = NULL)
    {
    if( array_key_exists($var, $this->_get) ) {
    return $this->_get[$var];
    } else {
    return FALSE;
    }
    }

    function get_all($var = NULL)
    {
    return (array)$this->_get;
    }

    function post($var = NULL)
    {
    if( array_key_exists($var, $this->_post) ) {
    return $this->_post[$var];
    } else {
    return FALSE;
    }
    }

    function post_all($var = NULL)
    {
    return (array)$this->_post;
    }
    }

    To use, add $this->input = new Input(); to your __construct() method in Controller and you’ll be able to do this within your controller:

    $id = $this->input->get(‘id’);

    $username = $this->input->post(‘username’);
    $password = $this->input->post(‘password’);

    This Input.php library also makes it quite easy to sanitize data on the fly (one reason why you might go this direction instead of directly accessing $_GET and $_POST and sanitizing them later). Lastly, this handles query strings and posted form data and is not to be confused with function arguments specified in the URI requiring assistance of .htaccess (e.g. yourapp/index.php/controller/arg1/arg2)

  • http://www.twitter.com/mattborja/ Matt Borja

    Not sure if this will work better. Last post didn’t post correctly…

    Here is a nice little library much similar to that used in CodeIgniter. I have this saved in application/libraries/Input.php and is included (or required) in my core.php (I use core.php instead of tinyMvc.php).

    <?php

    class Input {

    private $_get = array();
    private $_post = array();

    function __construct()
    {
    parse_str($_SERVER['QUERY_STRING'], $this->_get);

    $this->_post = $_POST;
    }

    function get($var = NULL)
    {
    if( array_key_exists($var, $this->_get) ) {
    return $this->_get[$var];
    } else {
    return FALSE;
    }
    }

    function get_all($var = NULL)
    {
    return (array)$this->_get;
    }

    function post($var = NULL)
    {
    if( array_key_exists($var, $this->_post) ) {
    return $this->_post[$var];
    } else {
    return FALSE;
    }
    }

    function post_all($var = NULL)
    {
    return (array)$this->_post;
    }
    }

    To use, add $this->input = new Input(); to your __construct() method in Controller and you’ll be able to do this within your controller:

    $id = $this->input->get(‘id’);

    $username = $this->input->post(‘username’);
    $password = $this->input->post(‘password’);

    This Input.php library also makes it quite easy to sanitize data on the fly (one reason why you might go this direction instead of directly accessing $_GET and $_POST and sanitizing them later). Lastly, this handles query strings and posted form data and is not to be confused with function arguments specified in the URI requiring assistance of .htaccess (e.g. yourapp/index.php/controller/arg1/arg2)

  • http://www.sz-media.org Nico Poggenburg

    A bit fast :D but a perfect example for beginners!

  • Miki

    This is so cool, it would be nice to expand its support for database !!!!!!!!

  • http://www.twitter.com/mattborja/ Matt Borja

    An object relational mapper of sorts would be highly suitable for something like this. You’ll have to be careful to test them thoroughly for performance issues. I recently discovered serious limitations with ActiveRecord and DataMapper (both on CodeIgniter) throwing memory exhaustion errors. That eventually led me to consider alternative solutions ranging from writing database libraries from scratch to writing an MVC platform from scratch.

    Haven’t tested its limits yet, but I was able to implement this in just a couple minutes into tinyMvc:

    http://www.phpactiverecord.org/projects/main/wiki/Quick_Start

    Of course there are others out there if you search for ORMs for PHP. Optimizations are good at these early stages when your MVC hasn’t had a chance to get real bloated yet.

    • Lex

      First time I see php activerecord, and I’m in love! What would be the best way to going about setting activerecord up on the tutorial – in terms of folder organization and where to include php active record from?

  • http://www.imstillreallybored.com Josh Bedo

    Thanks a lot for this video tutorial i was actually just looking for something like this on snipplr a few days ago but this version is much better than anything i found and it also works exactly like any open-source MVC framework.

  • http://www.vidhi-comp-cs.com Sandip Patel

    I have a question about the Editor that you are using for code. I tried to google but could not find. Is it available for free , and for windows ?

    You moved through the files during the demo very fast with the editor that I want try that to develop PHP codes.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      It’s called MacVim. For Windows, check out GVim.

  • http://khalidadisendjaja.web.id Khalid

    Check this out https://github.com/kh411d/no-framework-php , can be used for mvc or else

  • Alex

    Jeff,

    That was a simple yet cool tut.

    Would you consider extending it into a mini series? I think some of us would benefit in seeing how you would further extend the framework to include useful methods.

    Thanks.

  • Steve

    Now excuse my ignorance in this matter. But I am just a little curious why you need to have an index.php page and a tinyMVC.php page? I’ve seen this is also done on systems like joomla and wordpress, but I’ve never understood why you don’t just put everything on the index.php page. Especially in this case where there are only 2 lines on the index.php page. Surely it’s a waste?

  • http://goztansiyon.blogspot.com göz tansiyonu

    thanks for the tutorial (:

  • Anthony

    Thanks for yet another great tutorial Jeff!

    Like many others here, I’d love to see you extend this tinyMVC into a series where we can learn how you would expand on this idea further.

    I’m reasonably new to MVC and would to see more tutorials on this and other frameworks.

    Thanks again!

  • Chris

    Nice Nelwyns!!!

    • Chris

      Opps! I meant Brownies.

  • http://aoberoi.me Ankur

    i’d also like to see this built out a little more with the htaccess and the part about figuring out which page to display at the end of __construct(). thanks!

  • http://hundevelopers.hu David Komorowicz

    Thanks!
    Good tutorial!

    But how can I check on which page am I?

    controller.php:
    // determine what page you’re on
    $this->home();

    • Alessandro Sena

      I guess you pass the page on the url and do the proper treatment in the controller, but it a guess >.<

    • SolidSquid

      I think usually you would use a url attribute and then do a re-write to disguise it. eg:

      http://www.blahblahblah.com?page=about (to get the page)

      Then point http://www.blahblahblah.com/about to the above with a url re-write

      the re-write is purely for appearance and a little bit of a security thing so that people can’t see what url attributes you’re using (and try to use them to access things they shouldn’t)

  • yankoff

    I always thought vim is something ugly until I saw this video.
    Which plugins do you use for macvim? To color the code like that and for an autocompletion.

  • http://www.elimcmakin.com Eli McMakin

    Jeff does it again. Awesome. Adding my vote to see this extended.

  • 4centimeter_

    Thank you Jeff, good tutorial! I’d love to see a follow-up to this, like having multiple controllers with basic routing, and etc.

  • James

    Looks fine already, Jeffrey. But perhaps, even as an small application, consider using parent classes for the MVC classes?

    Usually i run 1 singleton class where all MVC classes inherit from. This way, all objects have access to 1 error console. This means that all helper classes can be loaded on this object and be callable from other MVC classes. It has some security issues, but the idea is that every helper/class is usable by the MVC classes. Not the MVC classes itself.

    Anyway, i like it, keep on going with this :) It`s helpful for a lot, i know I would`ve appreciated it when i started working MVC!

  • http://www.pixly.se Per Nissilä

    I’m a little of topic here but would you mind sharing what colorscheme that is for Vim?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Twilight.

  • Bruno

    Bravo!!!

    I would to see more!

  • Nouman

    Great info Jeff!

    Would love to see a second edition. I’ve tried to move forward myself. Got URLs to map nicely to classes and functions within them, but I’m positive my organization is a bit off.

    thanks again!

  • Justin

    nicce!! Make more video tutorials on this mvc plz! :)

  • Justin

    nicce!! Make more video tutorials on this mvc plz! :)

  • http://www.scottnelle.com/ Scott

    Another vote for building on top of this to create a series. Seems like a great direction to go for applications that aren’t a good fit for a pre-built system like wordpress of drupal and also aren’t complex enough for a full-on framework.

  • http://www.servetechit.co.uk/ Mike Hayes

    Great tutorial, thanks!

    I would like to see this developed further. I like the whole MVC concept but most frameworks aren’t too my liking or are too bloated – I would prefer to develop and use my own mini MVC framework suited to my own needs.

    If possible, it would be nice if there was an images/text tutorial to go with future upgrades to this. The video can be a pain to follow part by part (though I guess that I can download the source files and work from there after following the video).

  • http://codecanyon.net/user/robertnduati Robert Nduati

    Great tutorial!

    Added a routing class to evaluate the urls to determine the method in the controller class to use. Hope it will be of use to someone.

    It assumes the url is like this: http://yourdomain.com/tinyMvc/method/param1/param2/..
    It can also handle: http://yourdomain.com/tinyMvc/method/param1/param2/?va1=somethinf&var2=something..

    Add this to the constructor of the controller class:

    $this->router = new Router();
    $the_route = $this->router->get();
    eval($the_route);

    And then create this class:

    class Router {
    function get()
    {
    //APP_BASE_URL is a constant i set for the framwork. It is the full url to the
    //root folder of the framework
    $my_url = $this->str_replace_once(APP_BASE_URL, ”, $this->getfullurl());

    //This removes the query string part of the url so that it can be evaluated
    if($_SERVER["QUERY_STRING"]) {
    $my_url = $this->str_replace_once(“?” . $_SERVER["QUERY_STRING"], ”, $my_url);
    }
    $my_url = $this->trimTrailingSlashes($my_url);
    $requestURI = explode(‘/’, $my_url);
    $function = $requestURI[0];
    $parameters_str = ”;
    for($i = 1; $i ‘.$function.’(‘.$parameters_str.’);’;
    } else {
    return ‘$this->index();’;
    }
    }

    //THESE FOLLOWING FUNCTIONS ARE JUST HELPERS

    function str_replace_once($str_pattern, $str_replacement = ”, $string){
    if (strpos($string, $str_pattern) !== false){
    $occurrence = strpos($string, $str_pattern);
    return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
    }
    return $string;
    }

    function trimTrailingSlashes($str){
    $str = trim($str);
    return $str == ‘/’ ? $str : rtrim($str, ‘/’);
    }

    function getfullurl(){
    $s = empty($_SERVER["HTTPS"]) ? ” : ($_SERVER["HTTPS"] == “on”) ? “s” : “”;
    $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), “/”)) . $s;
    $port = ($_SERVER["SERVER_PORT"] == “80″) ? “” : (“:”.$_SERVER["SERVER_PORT"]);
    return $protocol . “://” . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
    }
    }

    you could also add a .htaccess file to the tinyMvc folder with this:

    RewriteEngine on
    RewriteCond $1 !^(index\.php|css|js|images)
    RewriteRule ^(.+) index.php/$1 [L]

    • http://codecanyon.net/user/robertnduati Robert Nduati

      The router class got messed up while posting. Your can get a working one from here:
      http://snipplr.com/view/49910/routing-class-for-tinymvc/

      • 4centimeter_

        Thanks Robert, but I guess, we also need some .htaccess with URL mod_rewrite?

    • Ben

      Robert thanks for this. I can get it to default and go to the $this-&gtindex.php but when I add a /method like:
      http://yourdomain.com/tinyMvc/method/
      I get a “Not Found error”. I’m guess the server is trying to look for a folder on the server instead of rerouting it like this class is suppose to do. Any thoughts?

  • Ryan

    Would love to see more advanced follow-ups to this tutorial. Awesome as always!

  • http://www.inversepenguin.com Julian

    Definitely a great introduction to MVC–I’m getting into PHP, and this is a great addition to my studies. I definitely have to watch it a few more times…

  • xristian matos

    MVC is the future, i think some open source projects like MOODLE must change its structure to MVC.

    Write less, do more

  • Sassy

    MOOOOOAR

  • http://www.inversecloud.com Julian

    I’ve gone through and setup my own micro MVC, followed by HTML5 Boilerplate integration… I’m ready to develop! Thanks again for the rundown… it really begins to make sense when you see it take form.

    +1 vote for more on tinyMVC.

  • Lex

    I’d also love to see this developed further!!!

  • http://zagalski.pl Zagal

    MVC in PHP is cool, but i found Python and Ruby more interesting.
    Btw. great screencast :P

  • Cody

    Great tutorial! Please make some more tutorials, would love to know the best way to have helper classes that can be included easily to do database connections, forms etc.

  • Warren Miller

    Like many others, I would love to see you do a follow up to this one Jeff; it’s awesome! Heck, you could even do a pretty good series on this, with different ways you could extend it. Rock on!

  • http://kebax.dk Kristian

    Hi…

    I’ve watched this and I’m still learning.

    Let’s say I have a site where I wanna use this tinymvc.

    I have a view called ‘site.php’ which is my “home” that loads at start. This site.php is responsible for all the css and html of the groundlayer of my site.

    My big question is then:
    In which of the MVC-files should I be making my functions? I’ve been having some problems locating how to use “$this->bla->bla”. And I found out that the only file I could successfully get access to was “load.php”. I thought was the “goto-file” from a view’s perspective?

    • Kristian

      Edit:

      I thought was the “goto-file” from a view’s perspective?

      –>

      I thought was the “goto-file” from a view’s perspective was the controller-file?

  • http://www.lukeinglis.com/ Luke

    More please. This was a great tut for me as I’m just cutting my teeth on both the MVC architecture pattern and PHP. Thanks.

  • Musa

    Great tutorial and funny tutorial image!

  • Dan

    Just what I have been looking for, would be great if there was a series of these. Seems to be a lack of MVC tutorials about online…

  • http://liime.net Andy Marshall

    Great tutorial, well done. I would love if you could expand it a bit as you said.

  • Žan

    I’d love to see you expand this into a MVC series. Specifically, showing how to route through multiple models, controllers and views.

  • Mr

    More MVC! More!

  • Reynald

    Hello! thank you very much for this tutorial! You saved me from much confusion. Please continue on with more in-depth tutorial regarding php MVC framework. =)

  • Alex

    Man nice tutorial, would love to see more of this or added to the market at least.

    Good job mate!