Tutorials

Embracing PHP 5.3 MVC with MiMViC

Mar 17, 2010 MaXPert 20 Comments

What is MiMViC?

MiMViC is a modular and lightweight PHP 5.3+ Web application framework designed to help build dynamic and robust Web sites. It’s theory is based on minimal and framework emphasizes on only core glue for your complex PHP web sites.

Today I will show you how to create a shout-box using the MiMViC framework. It won’t take you more than 15 mins to get the job done and have friendly URLs as well.

Requirements

So here are couple of things that we need to get started:

  • You are required to have PHP 5.3 for the framework to work. (Windows users can get a pre-configured package from here)
  • A Copy of the MiMViC Framewok. (Download)
  • A PHP language and mySQL knowledge

Now Let’s Build our Shoutbox!

In the root directory of your host create directory named shoutbox. Download and extract the uvic.php in the shoutbox directory. Now your shoutbox directory contains uvic.php file only. Next create a file named it index.php in the shoutbox directory, this file will initialize and include core components of mimvic. Paste the following code in the file:

First line enables strict error reporting for php, next we include the uvic.php and after that in next line we import the mimvic namespace as mvc alias (just for making our code short and quick). Finally we define the BASE_URL constant so that we can later on use it to generate our URLs.

I will be using .htaccess file with mod_rewrite to have more sexy URLs so let’s create that as well in the shoutbox directory. Here are the contents of .htaccess, just copy paste them:

This will help me make my urls look like http://localhost/shoutbox/view/from/2/upto/100 making them look cleaner and still re-directs my actions to index.php. So the BASE_URL contains the /shoutbox part of URI in case when I am not using mod_rewrite it will be /shoutbox/index.php (and http://localhost/shoutbox/view/from/2/upto/100 will become http://localhost/shoutbox/index.php/view/from/2/upto/100 ).

So let us install a hello world action and see if that works:

Add following lines of code before the mvc\start() call in index.php.

We are utilizing the full potential of PHP 5.3 here and registering two callback functions on these relative URIs (relative to http://localhost/shoutbox since our source lies there). Now hit the http://localhost/shoutbox/ and http://localhost/shoutbox/add to see the resulting echo from the registered functions.

Pretty simple and minimal, right? Now let’s connect to DB and get down some serious business. Lets remove the above two callback actions and make sure our index file has only these contents:

For shout box create a database named shoutbox you can use following SQL to create the table:

Once we have created table, we can come back to shoutbox folder and create a conf.php containing following code:

Again we just import the uvic.php and rename the namespace as done before. Next we create a PDO connection to database using the [username] and [password] credentials. The interesting part is we store this connection in mimvic storage facility so that later we can retrieve its value by mvc\retrieve(‘db’) anywhere globally in code, so rather than using global variable we will be asking MiMViC to store and retrieve values.

Now let’s create another file shout_actions that contains all the shout actions. Here lets register an action handler to view first 10 shouts, so paste following code in shouts_action.php:

In viewShouts function I have retrieved the latest 10 shouts, And made an array $data that will be passed to our view as data. So the view file must lie in views directory named view-shouts.php as passed to render function, here are the contents of view-shouts.php:

As you can see the variable stored at the ‘shouts’ index is available as variable here and similar is the matter with ‘error’; I have used the values inside them, iterated over them and displayed the entries. Let’s add the delete and add shout functionality for this I am going to add following piece of code to my shout_actions.php.

The above action will save the shout posted via POST method, so code is pretty self-explanatory, now let’s add the delete functionality and this time we are going to use URL parameters to pass parameters to it, and since we will invoke it URL in browser I will register it with get method, Here is the code:

The :id in URI tells mimvic to parse out the parameter passed in this segment of URI, and passes it at ‘id’ index of the associative array being passed to the callback function as parameter. Once I receive that parameter I plugged it into the SQL statement and executed it; once executed successfully I redirect back to root page. Now, we can add the following code for showing shout add form in view-shouts.php.

Similarly we can add the delete shout URL to the loop on $shouts so the block will look like:

Now, our basic shoutbox application is now ready. However a demo is not possible in this host because I am running a PHP version lower that 5.3.x. Download the framework and more examples here

Subscribe in my RSS Feed for free updates.

About the author: MaXPert

Expert & Freelancer in PHP, MYSQL, Javascript, including many frameworks like codeigniter, cakephp, mootools, jquery, prototype js and a long list.

  • Chris

    Well I have to say, this is simply powerful. I will definitely give it a try.

  • Daniel

    another syntax to learn?

  • http://eisbahn-stellingen.de/ Alex

    There is no space between “<?php" and "endforeach", "endif" and so on in view-shouts.php

    • http://maxpert.net.tc MaXPert

      Oppsss… fixed that

  • Pingback: Embracing PHP 5.3 MVC with MiMViC | INSIC DESIGNS | Coder Online

  • Pingback: 網站製作學習誌 » [Web] 連結分享

  • http://jordanryanmoore.com/ Jordan Ryan Moore

    error_reporting(E_STRICT) will enable E_STRICT errors, but it disables reporting every other type of error (E_NOTICE, E_WARNING). I’m guess what you really want is error_reporting(E_ALL | E_STRICT).

  • http://www.freelancephp.net Victor Villaverde Laan

    Looks very good! (still have to test it though)

    I also strive for minimalism. I like the idea of a very basic core which is easily extendable. Made a basic MVC myself (not ready for the public yet). And working now on a very basic JavaScript framework, which will be published soon.

    MaXPert, keep up the good work!

  • http://www.alfystudio.it alfy

    the server always returns the same error

    “Parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or ‘(‘ in C:\Programmi\Apache Software Foundation\Apache2.2\htdocs\mimvic\trunk\example\index.php on line 4″

    • http://maxpert.net.tc/ MaXPert

      You are using older version of PHP; please read the requirements carefully.

  • Bishop

    There is a missing space after RwriteRule, leading to an internal server error.
    RewriteRule^(.*)$ ./index.php/$1 [L]

    Thanks for that nice tutorial.

  • mike

    Dear MaXPert,

    Thanks for your marvelous MiMViC,I test the shoutbox today ,all’s ok.

    Best regards,
    Yours Mike,

  • mike

    I add this code:

    mvc\get(‘/view/:id’,

    function ($params){
    $stmt = mvc\retrieve(‘db’)->prepare(“select * from shouts where id = :id”);
    $stmt->execute( array(‘id’ => $params['id']) );
    $rs = $stmt->fetchAll();

    foreach($rs as $rss)
    {

    }
    $data = array(
    ‘a’ => $rss['name'],
    ‘b’ => $rss['shout']
    );

    mvc\render(‘view.php’, $data);
    }
    );

    this code works,I’m a beginner, could you show me the better one of this code

  • Pingback: 10 minute shout box with MiMViC using RedBeanPHP | INSIC DESIGNS

  • http://webmil.com.ua Vitaly

    You should try FatFree framework: http://fatfree.sourceforge.net/

  • Pingback: libro de visita en pocos minutos – con tbs « clicK-DIMension

  • http://www.ipter.com Leeann Merriam

    Hey! I’m at work browsing your blog from my new iphone 4! Just wanted to say I love reading through your blog and look forward to all your posts! Keep up the fantastic work!

  • Pingback: links for 2011-05-27 at Here I Rule

  • Pingback: 10 minute shout box with MiMViC using RedBeanPHP | XFloyd's blog

  • EllisGL

    How did anyone that commented get the above to work? It’s kind of hard to run with the 1.0 code when it can’t magically pull in files.

    index.php needs to have this added right before the “mvc\start();”:

    require_once ‘conf.php’;
    require_once ‘shouts_actions.php’;