Introduction

This tutorial will show you an example on how to we can separate front-end and back-end in Codeigniter 3. Front-end which is mainly used by public users who navigate through the site and sometimes register themselves to get updates on the site activities, new posts, update on a particular post etc. Back-end which is mainly used by site author, administrator, editor etc. to manage the site. So back-end will be restricted to some people with given roles.

Here I can use different URL, i.e., http://www.example.com/admin, for accessing directly admin login page or I can also use the URL http://www.example.com where login link is present on front-end header to navigate to the admin section.

Prerequisites

Codeigniter 3.1.10, PHP 7.0.15

Recommended reading: Setup HMVC with Codeigniter 3 tutorials for getting an idea for better understanding of the following implementation.

Example with Source Code

Step 1. Create a config file app_config.php with the following source code and put it under <project root>/application/config/

<?php

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

/*
  |--------------------------------------------------------------------------
  | Website Name
  |--------------------------------------------------------------------------
  |
  |Name of the Website
  |
 */

$config['site_name'] = 'www.roytuts.com';

/*
  |--------------------------------------------------------------------------
  | Message key
  |--------------------------------------------------------------------------
  |
  | Message key where message will be kept for future use
 */
$config['msg_key'] = 'msg_key';

/* End of file app_config.php */
/* Location: ./application/config/app_config.php */

Step 2. Verify <project root>/application/config/autoload.php with the following content.

$autoload['libraries'] = array('session', 'template', 'userauth');
$autoload['helper'] = array('url', 'form');
$autoload['config'] = array('app_config');

We have loaded built-in library – session along with our custom libraries – template and userauth. We will see how to create these custom libraries.

We have also loaded helper functions – url and form.

We have loaded our custom config file app_config, which we created in previous step.

Step 3. Check default controller is home in <project root>/application/config/routes.php. We will create this controller later.

$route['default_controller'] = 'home';

Step 4. We will use two different templates for front-end and back-end. So we need to create template configuration file <project root>/application/config/template.php.

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/*
  |--------------------------------------------------------------------------
  | Active template
  |--------------------------------------------------------------------------
  |
  | The $template['active_template'] setting lets you choose which template
  | group to make active.  By default there is only one group (the
  | "default" group).
  |
 */
$template['active_template'] = 'public';

/*
  |--------------------------------------------------------------------------
  | Explaination of template group variables
  |--------------------------------------------------------------------------
  |
  | ['template'] The filename of your master template file in the Views folder.
  |   Typically this file will contain a full XHTML skeleton that outputs your
  |   full template or region per region. Include the file extension if other
  |   than ".php"
  | ['regions'] Places within the template where your content may land.
  |   You may also include default markup, wrappers and attributes here
  |   (though not recommended). Region keys must be translatable into variables
  |   (no spaces or dashes, etc)
  | ['parser'] The parser class/library to use for the parse_view() method
  |   NOTE: See http://codeigniter.com/forums/viewthread/60050/P0/ for a good
  |   Smarty Parser that works perfectly with Template
  | ['parse_template'] FALSE (default) to treat master template as a View. TRUE
  |   to user parser (see above) on the master template
  |
  | Region information can be extended by setting the following variables:
  | ['content'] Must be an array! Use to set default region content
  | ['name'] A string to identify the region beyond what it is defined by its key.
  | ['wrapper'] An HTML element to wrap the region contents in. (We
  |   recommend doing this in your template file.)
  | ['attributes'] Multidimensional array defining HTML attributes of the
  |   wrapper. (We recommend doing this in your template file.)
  |
  | Example:
  | $template['default']['regions'] = array(
  |    'header' => array(
  |       'content' => array('<h1>Welcome</h1>','<p>Hello World</p>'),
  |       'name' => 'Page Header',
  |       'wrapper' => '<div>',
  |       'attributes' => array('id' => 'header', 'class' => 'clearfix')
  |    )
  | );
  |
 */

/*
  |--------------------------------------------------------------------------
  | Default Template Configuration (adjust this or create your own)
  |--------------------------------------------------------------------------
 */
//public template
$template['public']['template'] = 'templates/public/template';
$template['public']['regions'] = array(
    'title',
    'content'
);
$template['public']['parser'] = 'parser';
$template['public']['parser_method'] = 'parse';
$template['public']['parse_template'] = TRUE;

//admin template
$template['admin']['template'] = 'templates/admin/template';
$template['admin']['regions'] = array(
    'title',
    'content'
);
$template['admin']['parser'] = 'parser';
$template['admin']['parser_method'] = 'parse';
$template['admin']['parse_template'] = TRUE;

/* End of file template.php */
/* Location: ./config/template.php */

Step 5. We need to create form validation library to make codeigniter validation work correctly. Create below validation class at <project root>/application/libraries/my_form_validation.php.

<?php

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

class MY_Form_Validation extends CI_Form_validation {

    function run($module = '', $group = '') {
        (is_object($module)) AND $this->CI = &$module;
        return parent::run($group);
    }

}

/* End of file my_form_validation.php */
/* Location: ./application/libraries/my_form_validation.php */

Step 6. We loaded userauth library in autoload.php file above. Now create userauth library to authenticate users at <project root>/application/libraries/userauth.php. Note that all hardcoded values used here for demo purpose only and those values should come from database or any other external system as per your need.

<?php

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

define('STATUS_ACTIVATED', '1');
define('STATUS_NOT_ACTIVATED', '0');

/**
 * Description of UserAuth
 *
 * @author Admin
 */
class UserAuth {

    private $ci;
    private $msg;

    function __construct() {
        $this->ci = & get_instance();
        $this->ci->lang->load('msg');
    }

    /*
     * get message
     */

    private function get_msg($msg) {
        $this->msg .= $msg . "\r\n";
    }

    /*
     * display message
     */

    function display_msg() {
        return $this->msg;
    }

    /**
     * Login user on the site. Return TRUE if login is successful
     * (user exists and activated, password is correct), otherwise FALSE.
     *
     * @param	string	(email)
     * @param	string  (password)
     */
    function login($email, $password) {
        if ((strlen($email) > 0) AND (strlen($password) > 0)) {
            if ($email == '[email protected]') { // email ok --should be checked against database
                if ($password == 'admin') {  // password ok //should be checked against database
                        $this->ci->session->set_userdata(array(
                            'user_id' => 1, //should come from database
                            'user_email' => '[email protected]', //should come from database
                            'last_login' => '2015-05-05 12:00:25', //should come from database
                            'user_role' => 'admin', //should come from database
                            'user_status' => STATUS_ACTIVATED //should be checked against database
                        ));
                    return TRUE;
                } else {              // fail - wrong password
                    $this->get_msg($this->ci->lang->line('incorrect_password'));
                }
            } else {               // fail - wrong email
                $this->get_msg($this->ci->lang->line('incorrect_email'));
            }
        }
        return FALSE;
    }

    /**
     * Logout user from the site
     *
     * @return	void
     */
    function logout() {
        $this->delete_autologin();
        // See http://codeigniter.com/forums/viewreply/662369/ as the reason for the next line
        $this->ci->session->set_userdata(array('user_id' => '', 'user_email' => '', 'last_login' => '',
            'user_role' => '', 'user_status' => ''));
        $this->ci->session->sess_destroy();
    }

    /**
     * Get user role_id
     *
     * @param int
     * @return int
     */
    function get_role_id($user_id = 1) {
        return 1; //should come from database
    }

    /**
     * Check if user logged in. Also test if user is activated or not.
     *
     * @param	bool
     * @return	bool
     */
    function is_logged_in($activated = TRUE) {
        return $this->ci->session->userdata('user_status') === ($activated ? STATUS_ACTIVATED : STATUS_NOT_ACTIVATED);
    }

    /**
     * Get role name from role_id
     *
     * @param	string
     * @param	integer
     */
    function get_role_name($role_id = 1) {
        if ($role_id > 0) {
            return 'admin'; //should come from database
        }
        return '';
    }

    /**
     * Get user_id
     *
     * @return	string
     */
    function get_user_id() {
        if ($this->ci->session->userdata('user_id')) {
            return $this->ci->session->userdata('user_id');
        }
        return -1;
    }

    /**
     * Get username
     *
     * @return	string
     */
    function get_user_email() {
        if ($this->ci->session->userdata('user_email')) {
            return $this->ci->session->userdata('user_email');
        }
        return '';
    }

    /**
     * check logged in user is admin
     *
     * @param	string
     * @return	bool
     */
    function is_admin() {
        if ($this->ci->session->userdata('user_role')) {
            if (strtolower(trim($this->ci->session->userdata('user_role'))) === 'admin') {
                return TRUE;
            }
        }
        return FALSE;
    }

    /**
     * Get error message.
     * Can be invoked after any failed operation such as login or register.
     *
     * @return	string
     */
    function get_error_message() {
        return $this->msg;
    }

}

/* End of file userAuth.php */
/* Location: ./application/libraries/userauth.php */

Step 7. We loaded template library in autoload.php file above. Now create template library to load views at <project root>/application/libraries/template.php.

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 4.3.2 or newer
 *
 * @package CodeIgniter
 * @author  ExpressionEngine Dev Team
 * @copyright  Copyright (c) 2006, EllisLab, Inc.
 * @license http://codeigniter.com/user_guide/license.html
 * @link http://codeigniter.com
 * @since   Version 1.0
 * @filesource
 */
// --------------------------------------------------------------------

/**
 * CodeIgniter Template Class
 *
 * This class is and interface to CI's View class. It aims to improve the
 * interaction between controllers and views. Follow @link for more info
 *
 * @package		CodeIgniter
 * @author		Colin Williams
 * @subpackage	Libraries
 * @category	Libraries
 * @link		http://www.williamsconcepts.com/ci/libraries/template/index.html
 * @copyright  Copyright (c) 2008, Colin Williams.
 * @version 1.4.1
 * 
 */
class Template {

    var $CI;
    var $config;
    var $template;
    var $master;
    var $regions = array(
        '_scripts' => array(),
        '_styles' => array(),
        '_meta' => array()
    );
    var $output;
    var $js = array();
    var $css = array();
    var $meta = array();
    var $parser = 'parser';
    var $parser_method = 'parse';
    var $parse_template = FALSE;

    /**
     * Constructor
     *
     * Loads template configuration, template regions, and validates existence of 
     * default template
     *
     * @access	public
     */
    function __construct() {
        // Copy an instance of CI so we can use the entire framework.
        $this->CI = & get_instance();

        // Load the template config file and setup our master template and regions
        include(APPPATH . 'config/template' . EXT);
        if (isset($template)) {
            $this->config = $template;
            $this->set_template($template['active_template']);
        }
    }

    // --------------------------------------------------------------------

    /**
     * Use given template settings
     *
     * @access  public
     * @param   string   array key to access template settings
     * @return  void
     */
    function set_template($group) {
        if (isset($this->config[$group])) {
            $this->template = $this->config[$group];
        } else {
            show_error('The "' . $group . '" template group does not exist. Provide a valid group name or add the group first.');
        }
        $this->initialize($this->template);
    }

    // --------------------------------------------------------------------

    /**
     * Set master template
     *
     * @access  public
     * @param   string   filename of new master template file
     * @return  void
     */
    function set_master_template($filename) {
        if (file_exists(APPPATH . 'views/' . $filename) or file_exists(APPPATH . 'views/' . $filename . EXT)) {
            $this->master = $filename;
        } else {
            show_error('The filename provided does not exist in <strong>' . APPPATH . 'views</strong>. Remember to include the extension if other than ".php"');
        }
    }

    // --------------------------------------------------------------------

    /**
     * Dynamically add a template and optionally switch to it
     *
     * @access  public
     * @param   string   array key to access template settings
     * @param   array properly formed
     * @return  void
     */
    function add_template($group, $template, $activate = FALSE) {
        if (!isset($this->config[$group])) {
            $this->config[$group] = $template;
            if ($activate === TRUE) {
                $this->initialize($template);
            }
        } else {
            show_error('The "' . $group . '" template group already exists. Use a different group name.');
        }
    }

    // --------------------------------------------------------------------

    /**
     * Initialize class settings using config settings
     *
     * @access  public
     * @param   array   configuration array
     * @return  void
     */
    function initialize($props) {
        // Set master template
        if (isset($props['template'])
                && (file_exists(APPPATH . 'views/' . $props['template']) or file_exists(APPPATH . 'views/' . $props['template'] . EXT))) {
            $this->master = $props['template'];
        } else {
            // Master template must exist. Throw error.
            show_error('Either you have not provided a master template or the one provided does not exist in <strong>' . APPPATH . 'views</strong>. Remember to include the extension if other than ".php"');
        }

        // Load our regions
        if (isset($props['regions'])) {
            $this->set_regions($props['regions']);
        }

        // Set parser and parser method
        if (isset($props['parser'])) {
            $this->set_parser($props['parser']);
        }
        if (isset($props['parser_method'])) {
            $this->set_parser_method($props['parser_method']);
        }

        // Set master template parser instructions
        $this->parse_template = isset($props['parse_template']) ? $props['parse_template'] : FALSE;
    }

    // --------------------------------------------------------------------

    /**
     * Set regions for writing to
     *
     * @access  public
     * @param   array   properly formed regions array
     * @return  void
     */
    function set_regions($regions) {
        if (count($regions)) {
            $this->regions = array(
                '_scripts' => array(),
                '_styles' => array(),
                '_meta' => array()
            );
            foreach ($regions as $key => $region) {
                // Regions must be arrays, but we take the burden off the template 
                // developer and insure it here
                if (!is_array($region)) {
                    $this->add_region($region);
                } else {
                    $this->add_region($key, $region);
                }
            }
        }
    }

    // --------------------------------------------------------------------

    /**
     * Dynamically add region to the currently set template
     *
     * @access  public
     * @param   string   Name to identify the region
     * @param   array Optional array with region defaults
     * @return  void
     */
    function add_region($name, $props = array()) {
        if (!is_array($props)) {
            $props = array();
        }

        if (!isset($this->regions[$name])) {
            $this->regions[$name] = $props;
        } else {
            show_error('The "' . $name . '" region has already been defined.');
        }
    }

    // --------------------------------------------------------------------

    /**
     * Empty a region's content
     *
     * @access  public
     * @param   string   Name to identify the region
     * @return  void
     */
    function empty_region($name) {
        if (isset($this->regions[$name]['content'])) {
            $this->regions[$name]['content'] = array();
        } else {
            show_error('The "' . $name . '" region is undefined.');
        }
    }

    // --------------------------------------------------------------------

    /**
     * Set parser
     *
     * @access  public
     * @param   string   name of parser class to load and use for parsing methods
     * @return  void
     */
    function set_parser($parser, $method = NULL) {
        $this->parser = $parser;
        $this->CI->load->library($parser);

        if ($method) {
            $this->set_parser_method($method);
        }
    }

    // --------------------------------------------------------------------

    /**
     * Set parser method
     *
     * @access  public
     * @param   string   name of parser class member function to call when parsing
     * @return  void
     */
    function set_parser_method($method) {
        $this->parser_method = $method;
    }

    // --------------------------------------------------------------------

    /**
     * Write contents to a region
     *
     * @access	public
     * @param	string	region to write to
     * @param	string	what to write
     * @param	boolean	FALSE to append to region, TRUE to overwrite region
     * @return	void
     */
    function write($region, $content, $overwrite = FALSE) {
        if (isset($this->regions[$region])) {
            if ($overwrite === TRUE) { // Should we append the content or overwrite it
                $this->regions[$region]['content'] = array($content);
            } else {
                $this->regions[$region]['content'][] = $content;
            }
        }

        // Regions MUST be defined
        else {
            show_error("Cannot write to the '{$region}' region. The region is undefined.");
        }
    }

    // --------------------------------------------------------------------

    /**
     * Write content from a View to a region. 'Views within views'
     *
     * @access	public
     * @param	string	region to write to
     * @param	string	view file to use
     * @param	array	variables to pass into view
     * @param	boolean	FALSE to append to region, TRUE to overwrite region
     * @return	void
     */
    function write_view($region, $view, $data = NULL, $overwrite = FALSE) {
        $args = func_get_args();

        // Get rid of non-views
        unset($args[0], $args[2], $args[3]);

        // Do we have more view suggestions?
        if (count($args) > 1) {
            foreach ($args as $suggestion) {
                if (file_exists(APPPATH . 'views/' . $suggestion . EXT) or file_exists(APPPATH . 'views/' . $suggestion)) {
                    // Just change the $view arg so the rest of our method works as normal
                    $view = $suggestion;
                    break;
                }
            }
        }

        $content = $this->CI->load->view($view, $data, TRUE);
        $this->write($region, $content, $overwrite);
    }

    // --------------------------------------------------------------------

    /**
     * Parse content from a View to a region with the Parser Class
     *
     * @access  public
     * @param   string   region to write to
     * @param   string   view file to parse
     * @param   array variables to pass into view for parsing
     * @param   boolean  FALSE to append to region, TRUE to overwrite region
     * @return  void
     */
    function parse_view($region, $view, $data = NULL, $overwrite = FALSE) {
        $this->CI->load->library('parser');

        $args = func_get_args();

        // Get rid of non-views
        unset($args[0], $args[2], $args[3]);

        // Do we have more view suggestions?
        if (count($args) > 1) {
            foreach ($args as $suggestion) {
                if (file_exists(APPPATH . 'views/' . $suggestion . EXT) or file_exists(APPPATH . 'views/' . $suggestion)) {
                    // Just change the $view arg so the rest of our method works as normal
                    $view = $suggestion;
                    break;
                }
            }
        }

        $content = $this->CI->{$this->parser}->{$this->parser_method}($view, $data, TRUE);
        $this->write($region, $content, $overwrite);
    }

    // --------------------------------------------------------------------

    /**
     * Dynamically include javascript in the template
     * 
     * NOTE: This function does NOT check for existence of .js file
     *
     * @access  public
     * @param   string   script to import or embed
     * @param   string  'import' to load external file or 'embed' to add as-is
     * @param   boolean  TRUE to use 'defer' attribute, FALSE to exclude it
     * @return  TRUE on success, FALSE otherwise
     */
    function add_js($script, $type = 'import', $defer = FALSE) {
        $success = TRUE;
        $js = NULL;

        $this->CI->load->helper('url');

        switch ($type) {
            case 'import':
                $filepath = base_url() . $script;
                $js = '<script type="text/javascript" src="' . $filepath . '"';
                if ($defer) {
                    $js .= ' defer="defer"';
                }
                $js .= "></script>";
                break;

            case 'embed':
                $js = '<script type="text/javascript"';
                if ($defer) {
                    $js .= ' defer="defer"';
                }
                $js .= ">";
                $js .= $script;
                $js .= '</script>';
                break;

            default:
                $success = FALSE;
                break;
        }

        // Add to js array if it doesn't already exist
        if ($js != NULL && !in_array($js, $this->js)) {
            $this->js[] = $js;
            $this->write('_scripts', $js);
        }

        return $success;
    }

    // --------------------------------------------------------------------

    /**
     * Dynamically include CSS in the template
     * 
     * NOTE: This function does NOT check for existence of .css file
     *
     * @access  public
     * @param   string   CSS file to link, import or embed
     * @param   string  'link', 'import' or 'embed'
     * @param   string  media attribute to use with 'link' type only, FALSE for none
     * @return  TRUE on success, FALSE otherwise
     */
    function add_css($style, $type = 'link', $media = FALSE) {
        $success = TRUE;
        $css = NULL;

        $this->CI->load->helper('url');
        $filepath = base_url() . $style;

        switch ($type) {
            case 'link':

                $css = '<link type="text/css" rel="stylesheet" href="' . $filepath . '"';
                if ($media) {
                    $css .= ' media="' . $media . '"';
                }
                $css .= ' />';
                break;

            case 'import':
                $css = '<style type="text/css">@import url(' . $filepath . ');</style>';
                break;

            case 'embed':
                $css = '<style type="text/css">';
                $css .= $style;
                $css .= '</style>';
                break;

            default:
                $success = FALSE;
                break;
        }

        // Add to js array if it doesn't already exist
        if ($css != NULL && !in_array($css, $this->css)) {
            $this->css[] = $css;
            $this->write('_styles', $css);
        }

        return $success;
    }

    // --------------------------------------------------------------------

    /**
     * Dynamically include meta tags in the template
     * 
     * @param string $key meta name
     * @param string $value meta content
     * @return bool
     */
    function add_meta($key, $val) {
        $success = FALSE;
        $meta = '<meta name="' . $key . '" content="' . $val . '" />';

        if (!in_array($meta, $this->meta)) {
            $this->meta[] = $meta;
            $this->write('_meta', $meta);
            $success = TRUE;
        }

        return $success;
    }

    /**
     * Render the master template or a single region
     *
     * @access	public
     * @param	string	optionally opt to render a specific region
     * @param	boolean	FALSE to output the rendered template, TRUE to return as a string. Always TRUE when $region is supplied
     * @return	void or string (result of template build)
     */
    function render($region = NULL, $buffer = FALSE, $parse = FALSE) {
        // Just render $region if supplied
        if ($region) { // Display a specific regions contents
            if (isset($this->regions[$region])) {
                $output = $this->_build_content($this->regions[$region]);
            } else {
                show_error("Cannot render the '{$region}' region. The region is undefined.");
            }
        }

        // Build the output array
        else {
            foreach ($this->regions as $name => $region) {
                $this->output[$name] = $this->_build_content($region);
            }

            if ($this->parse_template === TRUE or $parse === TRUE) {
                // Use provided parser class and method to render the template
                $output = $this->CI->{$this->parser}->{$this->parser_method}($this->master, $this->output, TRUE);

                // Parsers never handle output, but we need to mimick it in this case
                if ($buffer === FALSE) {
                    $this->CI->output->set_output($output);
                }
            } else {
                // Use CI's loader class to render the template with our output array
                $output = $this->CI->load->view($this->master, $this->output, $buffer);
            }
        }

        return $output;
    }

    // --------------------------------------------------------------------

    /**
     * Load the master template or a single region
     *
     * DEPRECATED!
     * 
     * Use render() to compile and display your template and regions
     */
    function load($region = NULL, $buffer = FALSE) {
        $region = NULL;
        $this->render($region, $buffer);
    }

    // --------------------------------------------------------------------

    /**
     * Build a region from it's contents. Apply wrapper if provided
     *
     * @access	private
     * @param	string	region to build
     * @param	string	HTML element to wrap regions in; like '<div>'
     * @param	array	Multidimensional array of HTML elements to apply to $wrapper
     * @return	string	Output of region contents
     */
    function _build_content($region, $wrapper = NULL, $attributes = NULL) {
        $output = NULL;

        // Can't build an empty region. Exit stage left
        if (!isset($region['content']) or !count($region['content'])) {
            return FALSE;
        }

        // Possibly overwrite wrapper and attributes
        if ($wrapper) {
            $region['wrapper'] = $wrapper;
        }
        if ($attributes) {
            $region['attributes'] = $attributes;
        }

        // Open the wrapper and add attributes
        if (isset($region['wrapper'])) {
            // This just trims off the closing angle bracket. Like '<p>' to '<p'
            $output .= substr($region['wrapper'], 0, strlen($region['wrapper']) - 1);

            // Add HTML attributes
            if (isset($region['attributes']) && is_array($region['attributes'])) {
                foreach ($region['attributes'] as $name => $value) {
                    // We don't validate HTML attributes. Imagine someone using a custom XML template..
                    $output .= " $name=\"$value\"";
                }
            }

            $output .= ">";
        }

        // Output the content items.
        foreach ($region['content'] as $content) {
            $output .= $content;
        }

        // Close the wrapper tag
        if (isset($region['wrapper'])) {
            // This just turns the wrapper into a closing tag. Like '<p>' to '</p>'
            $output .= str_replace('<', '</', $region['wrapper']) . "\n";
        }

        return $output;
    }

}

// END Template Class

/* End of file Template.php */
/* Location: ./system/application/libraries/Template.php */

Step 8. Now we will create MY_Controller at <project root>/application/core/MY_Controller.php which will be extended by Public_Controller for front-end and Admin_Controller for back-end to meet extended functionality performed by those two different templates.

<?php

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

/* load the MX_Router class */
require APPPATH . "third_party/MX/Controller.php";

/**
 * Description of my_controller
 *
 * @author Administrator
 */
class MY_Controller extends MX_Controller {

    function __construct() {
        parent::__construct();
        if (version_compare(CI_VERSION, '2.1.0', '<')) {
            $this->load->library('security');
        }
        //no title for public and admin template
        $this->template->write('title', '', TRUE);
        $this->template->write('content', '', TRUE);
    }

}

/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */

Step 9. Create Public_Controller at <project root>/application/core/Public_Controller.php for front-end related view.

<?php

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

class Public_Controller extends MY_Controller {

    function __construct() {
        parent::__construct();
        // logic for template
    }

}

/* End of file Public_Controller.php */
/* Location: ./application/core/Public_Controller.php */

Step 10. Create Admin_Controller at <project root>/application/core/Admin_Controller.php for back-end related view.

<?php

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

class Admin_Controller extends MY_Controller {

    function __construct() {
        parent::__construct();
        // logic for template
        $this->template->set_template('admin');
    }

}

/* End of file Admin_Controller.php */
/* Location: ./application/core/Admin_Controller.php */

Now for all other files you need to download the source code from the below link given at the bottom.

Testing the Application

When your home page is displayed

separating front end and back end in codeigniter

When you click on Signin link

separating front end and back end in codeigniter

Note: you may get signing error, so you need to fix the error.

Source Code

That’s all. Thank you for your reading.

Tags:

4 thoughts on “Separating Front-end and Back-end in Codeigniter

  1. When i try this code i found this error

    Use of undefined constant VIEWPATH – assumed ‘VIEWPATH’ in /opt/lampp/htdocs/front_admin/system/core/Exceptions.php on line 242

  2. Hi… nice tutorial, but i get an error:

    Message: Call to undefined method MY_Loader::_ci_load_class()
    Filename: C:\wamp64\www\code10split\application\third_party\MX\Loader.php
    Line Number: 165

    Line 165 reads: $this->_ci_load_class($library, $params, $object_name);

    As you did not cover the nature of these files in the tutorial, i’m not sure how to go about correcting the error. Any help would be greatly appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *