Skip to content


Writing a Php5 MVC Framework like Code Igniter Part1: Controller,view,registry,loader

Some times we want a  flexible and basic framework for our small pretty applications. In this tutorial (in section part 1) we will start a  base framework  using MVC structure , we will create a Controller , View (template system) and  some base structures like  Registry - Loader. i call it Obullo framework. 

Below the picture show directory structure of Obullo framewok.

obullo framework directory structure

obullo framework directory structure

First of all we gonna go write registry file for register every declared classes as static. 

/**
 * Obullo Framework (c) 2009.
 *
 * PHP5 MVC Framework software for PHP 5.2.4 or newer
 *
 * @package        obullo
 * @filename        system/libraries/Registry.php
 * @author          obullo.com
 * @copyright      Ersin Güvenç (c) 2009.
 * @since            Version 1.0
 * @filesource
 * @license
 */

abstract class Obullo_Registry
{
    abstract protected function get($key);
    //get stored object.
    abstract protected function set($key,$val);
    //set (store) object.
} 

Class Object_Registry extends Obullo_Registry {

    /**
    * Registry array of objects
    * @access private
    */
    private static $objects = array();

    /**
    * The instance of the registry
    * @access private
    */
    private static $instance;

    //prevent directly access.
    private function __construct(){}
    //prevent clone.
    public function __clone(){}

    /**
    * singleton method used to access the object
    * @access public
    */
    public static function singleton()
    {
        if(!isset(self::$instance))
        {
        self::$instance = new self();
        //echo "new instance";
        } else {
        //echo "old instance";
        }
        return self::$instance;
    }

    protected function get($key)
    {
        if(isset($this->objects[$key]))
        {
            return $this->objects[$key];
        }
        return NULL;
    }

    protected function set($key,$val)
    {
        $this->objects[$key] = $val;
    }

    //static get request handle
    static function getObject($key)
    {

        return self::singleton()->get($key);
    }

    //store object
    static function storeObject($key, $instance)
    {

        return self::singleton()->set($key,$instance);
    }

} //end of the class.

/**
* Registry Controller Function
* @param - 1  string   name of the class its not instance.
* @param - 2  array    __construct params of instance.
* @access public
*/

function Register($class)
{
    $Obj = Object_Registry::singleton();

    $Class = strtolower($class); //lowercase classname.

    //if class already stored we are done.

    if ($Obj->getObject($Class) !== NULL)
    {
        //echo "ok";
        return $Obj->getObject($Class);

    }                           

    if(file_exists(SYS.'libraries'.DIRECTORY_SEPARATOR.ucfirst($Class).EXT))
    {
        require(SYS.'libraries'.DIRECTORY_SEPARATOR.ucfirst($Class).EXT);

    } elseif(file_exists(APP.'libraries'.DIRECTORY_SEPARATOR.$Class.EXT)) 

    {
        require(APP.'libraries'.DIRECTORY_SEPARATOR.$Class.EXT);
    }

    //declare class instance.
    //store object.
    $classname = ucfirst($class);
    $Obj->storeObject($Class, new $classname()); 

    //return singleton object.
    $Object = $Obj->getObject($Class);

    if(is_object($Object))
    return $Object;

} //end function.

We talk about PHP5 registry before at here: php5-object-registry-implementation-a-registry-design-pattern
We have a registry function now we can create main Controller file.


/**
 * Obullo Framework (c) 2009.
 *
 * PHP5 MVC Framework software for PHP 5.2.4 or newer
 *
 * @package         obullo
 * @filename        system/libraries/Controller.php
 * @author          obullo.com
 * @copyright       Ersin Güvenç (c) 2009.
 * @since           Version 1.0
 * @filesource
 * @license
 */                       

class OB_root extends Loader
{

public $load;
    //or storeObject(key,$this) getObject
    private static $instance;

    public function __construct()
    {
        parent::__construct();
        $this->load = $this;
        //self::$instance = $this;
        self::$instance = $this->load;

    }

    public static function getInstance()
    {
        return self::$instance;
    }

}

Class Controller extends OB_root
{

    function __construct()
    {

        $this->ob_init();
        parent::__construct();
        //$this->db   = Register('Db');
    }

    function ob_init()
    {
      /*
      *  we assing to load variable main loader class.
      *  we will use loader like this
      *  $this->load->library('file') //load class from library dir.
      *  $this->load->helper('file')  //load helper file from helper dir.
      */
      //$this->load =& Register('Loader');

      //load internal system classes...
      //WE CAN USE THIS CLASSES in controller like  $this->cookie->item
      //without use load word.

      $Classes = array(
                        'session'    => 'Session',
                        'cookie'     => 'Cookie'
                        );

        foreach ($Classes as $public_var => $Class)
        {
            $this->$public_var = Register($Class);
        }

        //from now on we can use session class
        //like this $this->session->set(); 

    } //end function.

} //end of the class.

//Get Super Object's Instance.
function OB_instance()
{
    return OB_root::getInstance();
}  

User Controller file (Controller/test.php) extends to Main Controller file and Main Controller initialize Obullo system classes.Now we need to a loader file for $this->load->view, $this->load->library operations.


/**
 * Obullo Framework (c) 2009.
 *
 * PHP5 MVC Framework software for PHP 5.2.4 or newer
 *
 * @package         obullo
 * @filename        system/libraries/Loader.php
 * @author          obullo.com
 * @copyright       Ersin Güvenç (c) 2009.
 * @since           Version 1.0
 * @filesource
 * @license
 */ 

Class Loader
{

    function __construct(){}

    /*
    *  Load classes from application/libraries directory.
    */
    public function library($class='')
    {
        if ($class == '') return false;

        $Clasname   = ucfirst(strtolower($class));
        $PublicVar  = strtolower($class);

        // Instantiate the Super Object.
        $OB =& OB_instance();
        $OB->$PublicVar = Register($class);

        //from now on we can use own library
        //like $this->Myclass->myMethod
    }

    /*
    *  main view function.
    */
    public function view($view, $data=array(), $string=false)
    {
        $file = VIEW . DIRECTORY_SEPARATOR . $view . EXT;
        if(sizeof($data) > 0)
        extract($data, EXTR_SKIP);
        //foreach($data as $key=>$value) $$key = $value;

        if (file_exists($file)) {

                if($string) {

                //get file as a srtring.
                ob_start();

                //look at code igniter similarity ->> system/libraries/loader.php line 671.
                //echo eval(file_get_contents($file));
                include($file);

                $content = ob_get_contents();
                ob_end_clean();

                return $content;

                } else {

                //just include file.
                include($file);
                }

        } else {
            die("Can't load template file: " . $file);
            //throw new Exception..
            return false;
        }

        return true;
    }

    public function model()
    {
       //we will write it later..
    }

} //end of the class.

We extends from Controller file to Loader and we can use call classes as $this->load->library(class).Loader file contains view and model structures..
Now we create our first Controller/test.php file.


/*
*  Our first controller controllers/test.php
*
*/

Class Test extends Controller
{

public $sample_var = "you can use variable from view";    

    function __construct()
    {
        parent::__construct();

        //load your class.
        $this->load->library('myclass');

    }                               

    function run()
    {
        echo "Run function succesfully works.<br /><br />";

        $data['sample_array'] = array('1','2','3','4','5');
        $data['example_var'] = "Hello World!";

        //example library class.
        $this->myclass->testMe(1,2); 

        echo "<br />";

        //example a system/library class: session.
        $this->session->set("test","Session variable succesfully works!");
        echo $this->session->get("test");

        //example view.
        $this->load->view("view_test_run",$data);
        //fetch as string  $this->view("run",$data,true);
    }

} //end of the class.

and we can run index.php file


$OB = new $Class();
//You can also set a var from outside of the class like this.
//$OB->name = "My Name";

$arg_array = array(); //write your arguments here...
call_user_func_array(array($OB, $Method), $arg_array);

and result..

Result

Result

Download .Zip File: Obullo Framework 1.0

  • Facebook
  • Digg
  • Delicious
  • Google Bookmarks
  • Technorati Favorites
  • Yahoo Bookmarks
  • Webnews
  • Technotizie
  • Taggly
  • Linkatopia
  • Ping
  • StumbleUpon
  • Twitter
  • Share/Bookmark

Posted in php articles.

Tagged with , , , , , , .


12 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Way says

    Really really good work. I came across to this site and saw this article.
    I like codeigniter but your implementation seems to be more pleasent for me.

    Keep on going this, I’d like to see part 2 of this article.

    So long.

  2. admin says

    Thanks. I will add database support and php5 input filter class for next version.I hope it will be a good framework because of it derived from Code Igniter.

  3. ron says

    hi
    will there be a part 2?

  4. admin says

    i will write part 2 when the finish Model and Database implementation.

    In part 2 i will tell
    -Php5 Exceptions
    -Model Implementation
    -Database Class

  5. xtc2xl says

    Thanks for a great tutorial, been reading up on alot lately but none come close to this. Looking forward to Part 2 of this tutorial set.

    Keep up the good work. Lates.

  6. admin says

    I guess next tutorial will be very good, model implementation, integrate the PHP5 PDO class to obullo DB, Exceptions, Error handlers completed just i will add some PDO functions.
    Please Subscribe to blog for hear next article.

  7. xtc2xl says

    Database is nice but a router class would be sexy too ;) I’m curious at your solution for the router to steer the whole framework.

    All these frameworks out today are overloaded with unnecessary code unlike this one created by you. Which not only makes it great for learning but also refreshing to code in.

    Thanks again seriously grade A tut.

  8. admin says

    after that part2 i will look at your router sample and i will implement a router class.. :) (in part 3)

  9. Alex says

    I really like this, i’ve been trying to do my own but i get stuck on stuff. I will be looking forward to the next one.

  10. nithin says

    great,
    Thanks

Continuing the Discussion

  1. Obullo -> Codeigniter php5 framework linked to this post on 03/06/2010

    [...] [...]



Some HTML is OK

or, reply to this post via trackback.



Easy AdSense by Unreal