Posted by Arjun on Sunday 29th January 2012

Base Controller In CodeIgniter

I always use this Base Controller for My CodeIgniter App Development, It makes my app portable and flexible.We can define all Global settings in Base Controller(Inheritable) so that all Child Controllers share some common methods and properties. Here is my Base Controller

application/core/MY_Controller.php

<?php if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class MY_Controller extends CI_Controller
{

    //Page info
    protected $data = array();
    protected $pageName = false;
    protected $template = "main";
	protected $skeleton = 'skeleton';
    //Page contents
    protected $javascript = array();
    protected $css = array();
    protected $fonts = array();
    //Page Meta
    protected $title = false;
    protected $description = false;
    protected $keywords = false;
    protected $author = false;
	protected $breadcrumbs = false;
	

    function __construct()
    {

        parent::__construct();
        $this->title = $this->config->item('site_title');
        $this->description = $this->config->item('site_description');
        $this->keywords = $this->config->item('site_keywords');
        $this->author = $this->config->item('site_author');
        $this->pageName = strToLower(get_class($this));
    }

    protected function _render($view, $renderData = "FULLPAGE")
    {
        switch ($renderData) {
            case "AJAX":
                $this->load->view($view, $this->data);
                break;
            case "JSON":
                echo json_encode($this->data);
                break;
            case "FULLPAGE":
            default:
                $toTpl["javascript"] = $this->javascript;
                $toTpl["css"] = $this->css;
                $toTpl["fonts"] = $this->fonts;
                $toTpl["title"] = $this->title;
                $toTpl["description"] = $this->description;
                $toTpl["keywords"] = $this->keywords;
                $toTpl["author"] = $this->author;
		$toTpl["breadcrumbs"] = $this->breadcrumbs;
	        $toBody["content_body"] = $this->load->view($view, array_merge($this->data, $toTpl), true);
                $toBody["header"] = $this->load->view("template/header",'', true);
                $toBody["footer"] = $this->load->view("template/footer", '', true);
                $toTpl["body"] = $this->load->view("template/" . $this->template, $toBody, true);
                $this->load->view("template/".$this->skeleton, $toTpl);
                break;
        }
    }

     protected function _is_ajax() {
        if (!$this->input->is_ajax_request()) {
            exit('No direct script access allowed');
       }
     }
}