CodeIgniter MVC Framework

Next Page Previous Page

Usually, when we create a web application we have to organize our code accordingly. But in Codeigniter, the architecture is pre-built in the form of MVC i.e. model, view, and controller. Everything is simplified and serrated from each other, we don't need to repeat a set of code again and again for the same feature for our application, we can easily reuse a set of code as many time as we like to

Model: showcases the data structure of your application, it holds all kinds of functions and interaction between database and application like CRUD operation.

  • Creating Model Class, Create a new file under application/models
<?php 

   Class Model_name extends CI_Model { 

      Public function __construct() { 

         parent::__construct(); 

      } 

   } 

?> 
  • Loading Model
$this->load->model('model_name');

 

  • And to call a Method from Model 
$this->model_name->method();

View: Views are simple HTML files that are used to display information through the user interface.

  • Let’s create a view together, Create a new file under application/views with the name “test.php”
<!DOCTYPE html> 

<html lang = "en"> 

   <head> 

      <meta charset = "utf-8"> 

      <title> My View Example</title> 

   </head>

   <body> 

       This is a Codeigniter View MyExample 

   </body>

</html>
  • Loading the View
<?php 

   class Test extends CI_Controller { 

      public function index() { 

         $this->load->view('mytest'); 

      } 

   } 

?>



Controllers: The controller binds the code, musters data back and forth between views and database.

 

  • Creating a Controller: to create a controller, we go to the application/controllers folder. We will create a new file with the same path named “MyTest.php”. 
<?php 

   class MyTest extends CI_Controller {

      public function index() { 

         echo "Our First Controller !"; 

      } 

   } 

?>
  • Calling a Controller: Let’s call our test Controller now 
http://www.somesite.com/index.php/mytest
  • And to call a specific method we will use 
http://www.somesite.com/index.php/test/Method_name
  • Let’s create a custom method for our controller 
<?php 

   class Test extends CI_Controller {  

      public function index() { 

         echo "Our First Controller !"; 

      }

         public function Custom_Method() { 

         echo "This is our default function."; 

      }  

   } 

?>

Summary :

  • MVC is a standard modular construction for web development.
  • MVC simplifies the complexities of core PHP.
  • No need of rewriting a similar block of code again and again.
  • The code is easy to manipulate and read.
Next Page Previous Page

Treding Tutorial

Popular Tutorials

to Learn now