CodeIgniter Beginner Tutorial 2–Introduction to MVC

In this tutorial I’m going to show you the basics of implementing MVC using CodeIgniter. MVC stands for Model View Controller and its commonly used to separate logic from presentation. The Model handles the database manipulation, the Controller handles the logic and the View handles the presentation. That’s all I can share to you since I’m not an expert in MVC.

 

Controllers

Let’s start playing with the controller. The controller is the guy which we will be call from the url and that is through the class name and functions. If that didn’t make sense, don’t worry we’ll work through an example so that you’ll understand things better. First you have to create a new php file, name it whatever you like and save it on the controllers folder which can be found in the following path.

 codeigniter/application/controllers

Then create a new class inside the php file that you have just created, just make sure that the filename and the class name is the same. For example if you have named your file x.php your class name should be x. And that class should extend the code igniter controller.

<?php
class x extends ci_Controller{


}
?>

Next create a function called index(), this function is the default function that’s going to be called if you access the x controller.

function index(){
	$data['name'] = 'Yoh Asakura';
	$data['course'] = 'BSIT';
	$this->load->view('viewdata', $data); //load viewdata
}

What we just did was to pass an array into the view called viewdata. This simply means that whenever we try to access the x controller, the viewdata page is being loaded.

 

Views

We still haven’t created the viewdata file so create a new file called viewdata or whatever you like just make sure to match it with the name of the view that you are loading in your index() function. So that if you are loading the view called viewdata, then you must also name your file viewdata.php. Be sure to save your file in the views folder. Here’s the path.

 codeigniter/application/views

Inside the viewdata.php file check if the name and course is actually set. If its set then we output both of them.

if(isset($name) && isset($course)){
	echo $name.'<br/>'.$course;
}

And that is the beauty of MVC, we are actually making our code more organized by separating the logic and the presentation through the use of controllers and views.

Back to our x controller. Declare another function and call it whatever you like. I’ll call mine zup(). This function simply echoes out What’s up world.

function zup(){
	echo "What's up world!";
}

You can access it by supplying the function name after the name of the controller. Something like the one below if your controllers class name is earth and your function name is zup().

codeigniter/index.php/earth/zup

 

Models

As I have said earlier models do the talking with the database, it is where you will perform the queries, it is where you will assign the results to arrays. Okay I guess I’m not making any sense again so here’s an example.

First create a new php file and save it inside the models folder.

 codeigniter/application/models

Then create a class called mods and make it extend the code igniter model class. In simple terms extending the model class is a way to make an identification that this file is actually a model. Well aside from the fact that you saved it inside the models folder.

Next, create a method called get_records() which we will be using to fetch the records from the testing table. In this example I used the active record class, a built in class in codeIgniter which makes it easier to insert, update and fetch records from a database.

function get_records(){
	$db_query = $this->db->get('testing'); //select all records from testing table
	if($db_query->num_rows > 0){ //check if the query returned anything
		foreach($db_query->result() as $v){ //loop through the results that was returned
			$records[] = $v->name; //create a new array item and assign it to the name field
		}
			
	}
	return $records;//return the values accumulated by the $records array
}

Here’s the sql query for creating the testing table. Just add some sample data after you have imported it to the database that you have specified to be used by CodeIgniter.

CREATE TABLE IF NOT EXISTS `testing` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(80) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

Next, create the controller which will utilize the model that we have just created. Name it mods_controller and extend the Controller class just like what we did on the first example.

class mods_controller extends ci_Controller{


}

Inside the class, declare the index() function as I have said earlier this function is the default function that is being loaded once you access the class where it was declared in this case the mods_controller class.

function index(){
	$this->load->model('mods'); //load the mods model
	$data['names'] = $this->mods->get_records(); //call the get_records() function and assign its returned value to an array
	$this->load->view('mods_view', $data); //load the view and supply the data that was returned from the model
}

Finally, create the view in which we will display the records that were returned. Name it mods_view.php. Simply print the whole array for now.

<?php
print_r($names);
?>

 

Conclusion

That’s it for the second tutorial in this CodeIgniter beginner series. You have learned how to use Models, Views, and Controllers in CodeIgniter.

3 thoughts on “CodeIgniter Beginner Tutorial 2–Introduction to MVC

  1. The codeigniter manual states” Models are PHP classes that are designed to work with information in your database” , but if i write methods unrelated to database in a model and load it like this

    Model
                 class Othermodel extends CI_Model
    	  {
                       public function mymethod()
    	  {
                           //code
                           }
               }
    
    Controller  
                    public function index()
              {
                     $data ['strings']=$this->Othermodel->mymethod();
            }
     
    

    and use foreach to iterate the array $data
    it really helps me to avoid all the cluttering of controller with method declarations,Is it proper to do it in this fashion.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s