Beginning Codeigniter Application Development


 Beginning Codeigniter Application Development  
 

I have already written few articles on codeigniter, however, didn’t written for the genuine beginners yet. But, as i have written many beginner level tutorials here, i think, a beginners tutorial on codeigniter will be also helpful for my blog readers. At the time of writing, the latest codeigniter version is 2.0.2 . I am going to use this version for today’s tutorial. This tutorial is intended to the developers who are absolute beginners on codeigniter and want to have a better start very quickly.

Prerequisites:

However, prior using codeigntier, its required that you know what mvc design pattern is. To more about mvc, you can start with the wiki article on mvc .

Also, wish you have already xampp/wamp or something similar already set up in your computer. Now, Download the latest version of codeigniter. extract it and copy the directory to the root of your local server. without doing anything else, you should be able to run this and see a page like as follows from this local url: http://localhost/codeigntier/

Running Codeigniter Firsttime

Read The Complete PHP CodeIgniter Tutorials Series By CodeSamplez.com

Directory Structure:

The application directory structure is mainly consists of 2 directory, ‘system’ and ‘application’.

Codeigniter Root Directory Structure

The ‘system’ directory is the core and consists of the core framework files. When a new version is released, you can update your existing application just by replacing this system directory with the latest release. We won’t never going to work on this folder our selves ever. All our codes are going to take place in the ‘application directory’. There you will see a list of sub directories as like the following image:

codeigniter application directory structure

Lets get a little familiar with the directories:

  • Cache : This directory will contain all kinds of cached files if you are using so. However, you will may need to provide write access for the application to this directory as codeigniter will need to create temporary files on this folder. To know how to use caching, please refer to codeigniter caching tutorial.
  • Config : This directory includes settings/configuration related information like database settings, route information, constants declaration, items to be auto loaded etc. To know more, please visit codeigniter documentation about using config class .
  • Controller : This directory includes all controller definitions. It can be said as the entry point of application also, every requests triggers a certain method of a controller.
  • Core : If we need to extend the functionality of any core classes like controller,loader,router etc, then we can declare new class here which will extend those core classes and put the implementation inside those.
  • Errors : This directory includes some basic template for showing various kind of errors like db error, php errors, 404 errors etc, which we can change later as per our requirements.
  • Helpers : This directory will include all helper files. Read more about using helpers.
  • Hooks : This directory will include all hooks declaration. Read more about using hooks
  • Language : This directory will include language files. By loading different language files, we can make our application multilingual supported. Read more about using language class.
  • Libraries : This directory will include all library class files that might need to be created for our applications.
  • Logs : This directory will include all application logs. TO know how to write log for debug/error/info, please more about error handling
  • Migrations : This directory will include migration helpers.
  • Models : This directory will include all model classes used in our application. This section can be said as the ‘data access layer’ of our application.
  • Third_party : This directory will include library files, but only those, which are imported from third-party. So, difference between the ‘third_party’ and ‘libraries’ is that, one is for self-made libraries, for app specific, other one is for importing party libraries.
  • Views : This directory will include all view template files.

Application URL Structure:

Codeigniter uses a very easy and handy url structure scheme. and it is completely inter-related with the controller class name and method name. to access a controller method, you have to use url like {root_url}/index.php/{controller_name}/{method_name}. To know more in details, please refer to the codeigniter url structure documentation .

Create A Basic Controller:

Lets start by making a basic controller class file. Create a new file in the ‘controllers’ directory and name it ‘blog.php’. Here is the code snippet for this controller class:

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

class Blog extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/blog
	 *	- or -  
	 * 		http://example.com/index.php/blog/index
	 *	- or -	
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/blog/{method_name}
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		echo "Hello World";
	}
}

/* End of file Blog.php */
/* Location: ./application/controllers/blog.php */

Now, run the application with the url “http://localhost/ci_app/index.php/blog”, you will see the sentence ‘Hello World’ on the page. ‘index’ the default method that is being executed when no other method is specified in url. And we understood one thing clearly, to create a page, we may ignore to have a model and/or a view file, but we must need a controller.

Create a model :

Lets create a simple model on our application. We won’t cover any database activity on this tutorial. But, its pretty easy. setup your database server info on the ‘config/database.php’. Then you can access database in either straight cut way or use codeigniter provided ‘active record’ library that helps a lot creating/executing sql query easily. You can read more on my another article about codeigniter active record class. Here is the code of the model class we will be using:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blogmodel extends CI_Model{
    
    /**
     * returns a list of articles
     * @return array  
     */
    function get_articles_list(){
        $list = Array();
        
        $list[0]->title = "first blog title";
        $list[0]->author = "author 1";
                
        $list[1]->title = "second blog title";
        $list[1]->author = "author 2";
        
        return $list;
    }
}
?>

Modify The Controller:

To use the data from model, lets change our controller code that will receive data from model and send it to the view for final rendering. Here is the modified version of the controller:

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

class Blog extends CI_Controller {

	public function index()
	{
            $this->load->model("blogmodel");   
            $articles = $this->blogmodel->get_articles_list();            
            $data["articles"] = $articles;
            $this->load->view('blog/index',$data);
	}
}

Create A View:

Lets create a simple view file that will show the data we get from the ‘blogmodel’ in a basic html template. Following is the template code:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>Welcome to Blog Page</title>

<style type="text/css">
body {
 background-color: #fff;
 margin: 40px;
 font-family: Lucida Grande, Verdana, Sans-serif;
 font-size: 14px;
 color: #4F5155;
}

a {
 color: #003399;
 background-color: transparent;
 font-weight: normal;
}

h1 {
 color: #444;
 background-color: transparent;
 border-bottom: 1px solid #D0D0D0;
 font-size: 16px;
 font-weight: bold;
 margin: 24px 0 2px 0;
 padding: 5px 0 6px 0;
}

code {
 font-family: Monaco, Verdana, Sans-serif;
 font-size: 12px;
 background-color: #f9f9f9;
 border: 1px solid #D0D0D0;
 color: #002166;
 display: block;
 margin: 14px 0 14px 0;
 padding: 12px 10px 12px 10px;
}

</style>
</head>
<body>
    <h1>Welcome To my blog</h1>
<?php
foreach($articles as $article)
{
?>
    <p>
        <h3><?php echo $article->title; ?></h3>
            By <strong><?php echo $article->author; ?></strong>
    </p>
    <br />
<?php
}    
?>
</body>
</html>

Calling a view from controller:

The above “Modify The Controller” already demonstrates how to call a view. However there are few things you will need to remember. A traditional codeigniter view is a simple php file with “.php” extension. You can place it anywhere inside the “views” directory. Just, you will have to mention the correct path inside the ‘views’ directory. Like if you have a view inside a “blog” directory(which resides in ‘views’ directory, of course). Then you will have to pass the view parameter as follows:

$this->load->view("blog/template_name");

Notice that, we haven’t use any extension(here .php) for the template name as it recognize it automatically.

Another important thing to remember is that, the second parameter is optional to call the view. If you have any data to pass to view, then pass it through the second parameter. If you haven’t, then you won’t have to pass any second parameter at all.

Also, data that are passed to view are parsed from associated array. Lets say, we are assigning and passing some data from controller to view. The controller code is as follows:

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

class Test extends CI_Controller {

	public function index()
	{           
            $data["name"] = "Md. Ali Ahsan Rana";
            $data["designation"] = "Software Engineer"; 
            $this->load->view('test',$data);
	}
}

The view code is as follows:

<!-- File name: test.php -->
<!-- Location: application/views/test.php -->

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Welcome to Test Page</title>
</head>
<body>
<h2>My Name is <?php echo $name; ?></h2>
<h2>My Designation is <?php echo $designation; ?></h2>
</body>
</html>

Notice that, every associative key from $data becomes as a variable on the view section. So, any data variable you may need on your view, you will have to wrap it with a common variable’s associative index(here $data variable) and finally pass this wrapper variable. Codeigniter will parse it automatically to its corresponding component variables.

References:

As long as you know the basics, best place to know in details is the codeigniter documentation. There you will find in details about every thing with examples also. I found it as one of the best documentation on web. You can ask any kind of question related to codeigniter on their official forum . Happy coding :)

Comments

    • says

      Are you having issues? Can you please explain what? Then I can try to solve it and also update the tutorial for being more helpful for future seekers. Thanks..

    • MichaelB says

      The first section does work, then the rest of the article becomes unclear.

      1. In the section “Create a model”, what should be the filename of that file?
      2. In the section “Create A View”, what should be the filename of that?

      • says

        Hi MichaelB, There is no specific restriction to the naming convention for model/view(or even controller). You can use any name, just you will have to remember to extend them from their corresponding base class. Like, if you are creating a model, you must have to inherit the “CI_Model” class, to get the characteristics of a regular Codeigniter model. In case of view, just name the template any name and then call it from controller with data(if any), Like as follows:

        $this->load->view(“template_name”,$data);

        I will edit the tutorial for calling a view from controller. Seems it will may helpful to some other guys like you. Thanks for pointing out is.

  1. says

    Really great programming abilities you\’ve there. i\’m a programmer myself but I still require to learn until I reach your ability. great article!

  2. bari says

    hi rana, i have problem with include php file. i use include(), require() and require_once(). but none of them works.
    i have a php file that contain only variables, so much variables. and i want to include the file to passing variables.
    how i supposed to do. pls help me.
    the ci directory:
    -application
    -system
    -user_guide
    -style
    -include_folder

    and my file in include_folder directory.

    thanks in advance.

  3. kamal says

    hello Rana,
    I’m a beginer in CI my problem is how to load jquery library in the current version of CI and how to apply a common CSS styling sheet to all my views

  4. pratik says

    great,i have one problem i want to pass the more then one query from the model and get in controller.now i want to some additional work on that query and pass to the view.how can i do that.thanks

  5. says

    Very useful especially on passing data to the view and how the keys of the associative array are automatically turned into variables in the view.

  6. Raza says

    the first program for blog.. throws an error more of a warnin. creating default object on empty value..

    • says

      Hello Raza, it seems like you php compatibility error. This exercize was written with php 5.3.x and you are probably using php 5.4 , right? Just initialize all the variables at first (example: $test = (object)NULL) solves the problem in most cases. If you are still not sure what to do, can you give the error line number or a screenshot link? Thanks.

  7. Azhar says

    i have this problem. I have created a views/templates/navbar.php using bootstrap. the bootstrap is located in the root directory assets/bootstrap. I called the navbar.php through the default controller (news). It works.

    Then I create another views/templates/page.php. I created a function create_cosec in the default controller with $this->load->view(‘navbar’); and $this->load-view(‘page.php’); . I wish the page will display the navbar on the top follow by the page details.

    When I call the page localhost/index.php/news/ create_cosec ==>the page is display correctly but the navbar displayed but without the bootstrap functionalities. It seems that codeigniter doesn’t know where is the assets/bootstrap directory?

    Is it URL issues?
    Thanks

Trackbacks

Leave a Reply