Thursday, September 12, 2013

Creating A Simple PHP MVC Framework Part Three (smarty version)

  Written by: Lorenzo D. Alipio  

In part two, we utilized the .htaccess for routing page requests to the web directory. In this series (part three), we will be creating bootstrap, autoloader, singleton instantiator or objects initialization class.

filename: /application/Bootstrap.php

<?php

/*
* 
* Copyright Lorenzo D. Alipio 
* 
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
* 
* Bootstrap.php
*/

if(!isset($_SESSION)){session_start();}
define('TPL','Smarty');
/*
*
* file constants definition file or bootstrap
*
*/
define( 'SITEPATH', $_SERVER['SERVER_NAME'] . str_replace($_SERVER['DOCUMENT_ROOT'], '', dirname($_SERVER['SCRIPT_FILENAME'])) .'/');

define ('EXT', '.php');
define ('DS', DIRECTORY_SEPARATOR);
define ('ROOT',(dirname(__DIR__)));
define ('TEMP',ROOT.DS .'temp'. DS );
define ('BASE_CONTROLLER', ROOT .'\vendor\core\controller_Controller');
define ('VENDOR', ROOT .'/vendor/');

/*
*Define Base model for the application
*@BASE holds database connection e.g. PDO, MYSQLI
*@MODEL application model e.g. IndexModel, YoutubeModel, the same convention as the controllers
*/

define ('BASE_MODEL',ROOT .'\vendor\core\model_Model');
define ('MODEL',ROOT .'\application\model_ModelClass');
define ('VIEW', ROOT .'\application\view_ViewClass');

/* libraries for the application */

define ('LIBS', ROOT.DS .'vendor\applib'. DS);
define ('TPL_ENG', LIBS .'template_engine'. DS);
define ('SMARTY_LOAD', LIBS .'\template_engine\smarty_Smarty.class');

/* Template engine configuration and directories */

## define public directory, accessable only to users
define ('WEB_DIR', ROOT. DS .'web'.DS);
## Theme Directory
                define( 'THEME_DIR', WEB_DIR .'themes'. DS );
                define( 'THEME_COMPILE', THEME_DIR .'themes_compile');
                define( 'THEME_CACHE', TEMP .'theme_cache'. DS);
                define( 'THEME_CONFIG', THEME_DIR .'theme_configs');
                define( 'THEME' , THEME_DIR .'green'. DS );
               

The function of the bootstrap.php above is to keep all of the files in our application. This is the page where we  define our constants. I am planning to write another tutorial similar to this, but it will be more advance than this. It will beutilizing the composer autoloader, and symfony class loader. Since this article is entitled as "simple MVC", I need to stay focus on that purpose.

Next, we will need to use some form of autoloader that is PSR-0 compliant. Since, we are creating a "Simple MVC", we will utilize fig-standards equivalent example for simplification. Also, we will be using simple singleton to load our classes.

 filename: /application/AutoLoad.php

<?php

/*
* 
* Copyright Lorenzo D. Alipio 
* 
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
* 
* AutoLoad.php
*/

require_once ('Bootstrap.file.php');


class Use_Class{

    /*
     *  @autoload autoload class file.
     *  
     *  @param [in] $className class file constant name
     *  @return require_once the file
     */
public static function autoload($className)
{
  
    $className = ltrim($className, '\\');
    $fileName  = '';
    $namespace = '';
    if ($lastNsPos = strrpos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    

    require_once $fileName;
}
/*
*@loadController 
*@controller takes pathinfo
*@return PagecontrollerController or default IndexController
*/
public static function loadController($controller,$array=array()){
    
return((is_array($array) && ((!empty($controller) || ($controller != null) )))? array('\application\controller_'.ucfirst($controller).'Controller' , array_search($controller, $array)) : array('\application\controller_IndexController' ,'IndexController'));

}
public static function useFile($file){
    include_once($file);
}
}

/*
*
*@ini_Object initialize objects by singleton
*return objects
*/
final class Ini_object{
 
    /**
     * Maintains collection of instantiated classes
     */
    private static $instances = array();
    
    /**
     * Overload constructor
     */
    private function __construct(){}
    
    /**
     * Manages instantiation of classes
     * 
     * @param $class
     * 
     * @return self instance of the class
     */
    public static function instance($class)
    {        
        //instantiate class as necessary
        self::create($class);    
        
        //return instance
        return self::$instances[$class];
    }
    
    /**
     * Creates the instances
     * 
     * @param $class
     * 
     * @return none
     */
    private static function create($class)
    {
        //check if an instance of requested class exists
        if (!array_key_exists($class , self::$instances))
        {
            self::$instances[$class] = new $class;
        }
    }
}

/*
*@auto load base controller model, view and smarty
*/
Use_Class::autoload(BASE_CONTROLLER);
/*
*@auto load application model.. this is not the base model
*@auto load application view .. this is not the base view class
*/
Use_Class::autoload(MODEL);
Use_Class::autoload(VIEW);
Use_Class::autoload(SMARTY_LOAD);


The autoload.php above contains two classes, the first one is the Use_Class() class and the second is the Ini_Object which will serve the instances of a class as requested throughout our application. Below the page are instances of the base controller, application model, application view, and the smarty object. Later, we will be installing the Smarty template engine. Let's take care of the crucial files first, then we half-step back to make sure the smarty template files are unzipped into the proper directory.

Once again this post is getting really long, I must conclude this series and continue to build our application core files in part four of the series.

No comments:

Post a Comment