More

    Setting Up CodeIgniter Project | Part-4

    Today I’m going to guide on setting up the CodeIgniter project. Before proceeding forward, please read my blog on CodeIgniter File Structure and Architecture. This post gives you ideas about how the framework stores individuals’ files and contributes to the project.

    Different configuration for your web applications

    Setting up autoload

    Go to “application/config/autoload.php” file. It contains all the configuration code that the framework loads by default. The framework loads absolute files at the beginning to keep the framework light-weight.

    CodeIgniter framework loads packages, libraries, drivers, helper files, custom config files, language files, and models.

    Just add the URL helper class at the beginning.

    $autoload['helper'] = array('url');

    You can add a list of libraries that should be auto loaded by your web application. You can add a database, email, session, etc. libraries.

    $autoload['libraries'] = array('database', 'email', 'session');

    Setting up config

    Go to “application/config/config.php” file. It contains all the configuration code that configures your CodeIgniter project. You can set a cross-site request forgery cookie here.

    We are going to setup base_url. sAdd the following code on base_url

    $config['base_url']  =  "http://".$_SERVER['HTTP_HOST'];
    $config['base_url'] .= preg_replace('@/+$@', '', dirname($_SERVER['SCRIPT_NAME'])).'/';

    Setting up the database

    Database Design
    Database Design

    Go to “application/config/database.php” file. It contains all the configuration code that configure your CodeIgniter web application to the database. It has all the settings that need to access your CodeIgniter web application.

    I’m going to guide you through configuring basic settings that are required to connect the database. You should add the database hostname, username, password, database, dbdriver, etc.

    $db['default'] = array(
    	'dsn'	=> '',
    	'hostname' => 'localhost',
    	'username' => 'your username',
    	'password' => 'your password',
    	'database' => 'your database',
    	'dbdriver' => 'mysqli',
    	'dbprefix' => '',
    	'pconnect' => FALSE,
    	'db_debug' => (ENVIRONMENT !== 'production'),
    	'cache_on' => FALSE,
    	'cachedir' => '',
    	'char_set' => 'utf8',
    	'dbcollat' => 'utf8_general_ci',
    	'swap_pre' => '',
    	'encrypt' => FALSE,
    	'compress' => FALSE,
    	'stricton' => FALSE,
    	'failover' => array(),
    

    You can leave few options to their default values except

    • Hostname:- set the location of your database
    • Username:– set your database username
    • Password:– select your database password
    • Database:– set your database name
    • Dbdriver:- set types of the database you are using, i.e., MySQL, Postgre, ODBC, MS SQL, etc.

    Setting up routes

    Go to “application/config/routes.php” file. It contains all the configuration code to set up your CodeIgniter web application routing. You can define your routing rules in this file.

    I’ll define some routing rules later on setting up CodeIgniter Project blog.

    Controller

    Controllers are the heart/brain of your CodeIgniter web application are the heart/brain as it determines how your web application handles HTTP request. When your web application receives an HTTP request, your web application assigns the correct controller to process the HTTP request.

    The controller plays the intermediary roles between the model and the views to process the HTTP request.

    I’ll take an example of a random URL

    yoursite.com/index.php/login

    In this URL, yoursite.com is the domain name of your web application. It can be localhost when developed in a local development server. “index.php” accepts your HTTP request and assigns the respective controller. Here “Login.php” is the controller name.

    Hello World

    Controller Syntax

    CodeIgniter is a case sensitive, i.e., it must have correct spelling or the same spelling while coding.

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Sample extends CI_Controller {
    
    	public function index()
    	{
    		echo 'Hello World!';
    	}
    }
    

    The above code snippet configures a controller named “Sample.php.” The first letter should be uppercase. Make sure you extend the parent controller class so that it can inherit all its methods.

    Now you can visit your web application using the following URL

    yoursite.com/index.php/sample

    Method in Controllers

    Public function index() is the default method of the Sample controller.

    “Class name should always  start with an upper case.”

    <?php
    class Sample extends CI_Controller {
    
            public function index()
            {
                    echo 'Hello World!';
            }
    
            public function print()
            {
                    echo 'You are viewing dokocrunch.com';
            }
    }
    

    In the above code snippets, Sample is the controller class with two methods, i.e., index and print.

    Web application calls to index() method by default when there is no default method calling.

    You can call second method print() by the following URL

    yoursite.com/index.php/sample/print

    Constructor method

    If you are planning to use a constructor in your web application, then you must place the following code in your file.

    Parent::__construct();
    <?php
    class Sample extends CI_Controller {
    
            public function __construct()
            {
                    parent::__construct();
                    // Your own constructor code
            }
    }
    

    CodeIgniter URI segment

    yoursite.com/index.php/class/function/ID

    The CodeIgniter web application represents URL as

    The first segment represents controller class

    The second segment represents the method/function

    The third segment represents addition information, i.e., ID and any variables that passed to the controller.

    “Initializing the URL helper on autoload config is best practice.”

    Removing the index.php from URL

    By default, your CodeIgniter includes the “index.php” in your URL string. However, you can remove “index.php” from your URL string.

    You can easily remove this file using “.htaccess” file with simple rules.

    On your home directory, create a file with “.htaccess” and add following code.

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
    

    This above setting removes “index.php” from your web application. Any HTTP request except above, your web application treated URL as a request for “index.php” file.

    Setting your routing rules

    route navigation
    route navigation

    You can set your own routing rules with “application/config/routes.php” file. You can specify your routing criteria within “$route” code.

    Till now you have seen various examples like

    yoursite.com/class/function 

    This time you will see a different approach. In this approach, you will use your routing URL.

    Let’s suppose yoursite.com/product/showdetail shows the grocery product detail of an e-commerce site.

    You can write a different controller class with another name than a “Product.php” file. You can create a controller class with “Item.php” file. Remember you have to map your URL string with controller and function name.

    you can configure on “application/config/routes.php” as

    $route[product/showdetail] = item/productDetail';

    Setting up a CodeIgniter project is easy. I’ve shown you how to configure your web application. I hope you’ve got some information reading this post.

    Don’t forget to comment on how you feel about my content.

    Recent Articles

    spot_img

    Related Stories

    4 Comments

    Leave A Reply

    Please enter your comment!
    Please enter your name here

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Get new notification

    Subscribe to our newsletter

    To be updated with all the latest news, offers and special announcements.