Skip to main content

Simple CodeIgniter Tutorial


This Simple tutorial will primarily focus on:
  • Model-View-Controller basics
  • Routing basics
  • Form validation
  • Performing basic database queries using “Query Builder”

Adding logic to the controller :

Create a file at application-package_folder/controllers/Pages.php with the following code.
<?php
class Pages extends CI_Controller {

        public function view($page = 'home')
        {
        }
}
You have created a class named Pages, with a view method that accepts one argument named $page. The Pages class is extending the CI_Controller class. This means that the new pages class can access the methods and variables defined in the CI_Controller class (system/core/Controller.php).
The controller is what will become the center of every request to your web application. In very technical CodeIgniter discussions, it may be referred to as the super object. Like any php class, you refer to it within your controllers as $this. Referring to $this is how you will load libraries, views, and generally command the framework.
Now you’ve created your first method, it’s time to make some basic page templates. We will be creating two “views” (page templates) that act as our page footer and header.
Create the header at application/views/templates/header.php and add the following code:
<html>
        <head>
                <title>CodeIgniter Tutorial</title>
        </head>
        <body>

                <h1><?php echo $title; ?></h1>
The header contains the basic HTML code that you’ll want to display before loading the main view, together with a heading. It will also output the $title variable, which we’ll define later in the controller. Now, create a footer at application/views/templates/footer.php that includes the following code:
               <em>&copy; 2015</em>
        </body>
</html>


Adding logic to the view
Earlier you set up a controller with a view() method. The method accepts one parameter, which is the name of the page to be loaded. The static page templates will be located in the application-package_folder >/views/pages/ directory.
In that directory, create two files named home.php and about.php. Within those files, type some text − anything you’d like − and save them. If you like to be particularly un-original, try “Hello World!”.
In order to load those pages, you’ll have to check whether the requested page actually exists:
public function view($page = 'home')
{
        if ( ! file_exists(APPPATH.'views/pages/'.$page.'.php'))
        {
                // Whoops, we don't have a page for that!
                show_404();
        }

        $data['title'] = ucfirst($page); // Capitalize the first letter

        $this->load->view('templates/header', $data);
        $this->load->view('pages/'.$page, $data);
        $this->load->view('templates/footer', $data);
}

Now, when the page does exist, it is loaded, including the header and footer, and displayed to the user. If the page doesn’t exist, a “404 Page not found” error is shown.
The first line in this method checks whether the page actually exists. PHP’s native file_exists() function is used to check whether the file is where it’s expected to be. show_404() is a built-in CodeIgniter function that renders the default error page.
In the header template, the $title variable was used to customize the page title. The value of title is defined in this method, but instead of assigning the value to a variable, it is assigned to the title element in the $data array.
The last thing that has to be done is loading the views in the order they should be displayed. The second parameter in the view() method is used to pass values to the view. Each value in the $data array is assigned to a variable with the name of its key. So the value of $data['title'] in the controller is equivalent to $title in the view.

Routing

The controller is now functioning! Point your browser to [your-site-url]index.php/pages/view to see your page. When you visit index.php/pages/view/about you’ll see the about page, again including the header and footer.
Using custom routing rules, you have the power to map any URI to any controller and method, and break free from the normal convention:http://localhost/[controller-class]/[controller-method]/[arguments]
Let’s do that. Open the routing file located at application/config/routes.php and add the following two lines. Remove all other code that sets any element in the $route array.
$route['default_controller'] = 'pages/view';
$route['(:any)'] = 'pages/view/$1';
CodeIgniter reads its routing rules from top to bottom and routes the request to the first matching rule. Each rule is a regular expression (left-side) mapped to a controller and method name separated by slashes (right-side). When a request comes in, CodeIgniter looks for the first match, and calls the appropriate controller and method, possibly with arguments.
More information about routing can be found in the URI Routing documentation.
Here, the second rule in the $routes array matches any request using the wildcard string (:any). and passes the parameter to the view() method of the Pages class.
Now visit index.php/about. Did it get routed correctly to the view() method in the pages controller? Awesome!

Setting up your model

Instead of writing database operations right in the controller, queries should be placed in a model, so they can easily be reused later. Models are the place where you retrieve, insert, and update information in your database or other data stores. They represent your data.
Open up the application-package_folder/models/ directory and create a new file called New_model.php and add the following code. Make sure you’ve configured your database properly as described here.
<?php
class New_model extends CI_Model {

        public function __construct()
        {
                $this->load->database();
        }
} 
This code looks similar to the controller code that was used earlier. It creates a new model by extending CI_Model and loads the database library. This will make the database class available through the $this->db object.
Before querying the database, Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table:
$this->db->select('*'); 

$this->db->from('<table_name>'); 

/* db->where() function :

Identical to the above function except that it permits you to add a “where” clause in the second parameter, instead of using the db->where() function: only retrieve where condition records from a table
$this->db->where('<table_field_name>', $value);

*/

$data_record = $this->db->get();

return $data_record;
Add the following code to your model.
public function get_new($slug = FALSE)
{
     if ($slug != FALSE)
        {
               $this->db->where('name', $slug);
        }

  $this->db->select('*'); 

$this->db->from('new_table');

$data_record = $this->db->get();

return $data_record;

};

Display the new API

Now that the queries are written, the model should be tied to the views that are going to display the news items to the user. This could be done in our Pages controller created earlier, but for the sake of clarity, a new New_api controller is defined. Create the new controller at application-package_folder/controllers/New_api.php.
<?php
class New_api extends CI_Controller {

        public function __construct()
        {
                parent::__construct();
                $this->load->model('new_model');
                $this->load->helper('url_helper');
        }

        public function index()
        {
                $data['new'] = $this->new_model->get_new();
        }

        public function view($slug = NULL)
        {
                $data['new_item'] = $this->new_model->get_new($slug);
        }
}


Looking at the code, you may see some similarity with the files we created earlier. First, the __construct() method: it calls the constructor of its parent class (CI_Controller) and loads the model, so it can be used in all other methods in this controller. It also loads a collection of URL Helper functions, because we’ll use one of them in a view later.
Next, there are two methods to view all new items and one for a specific news item. You can see that the $slug variable is passed to the model’s method in the second method. The model is using this slug to identify the new_table item to be returned.
Now the data is retrieved by the controller through our model, but nothing is displayed yet. The next thing to do is passing this data to the views.
public function index()
{
        $data['news'] = $this->news_model->get_news();
        $data['title'] = 'News archive';

        $this->load->view('templates/header', $data);
        $this->load->view('new_api', $data);
        $this->load->view('templates/footer');
}

The code above gets all new_table records from the model and assigns it to a variable. The value for the title is also assigned to the $data['title'] element and all data is passed to the views. You now need to create a view to render the new_table items. Create application-package_folder/views/new_api.php and add the next piece of code.
<h2><?php echo $title; ?></h2>

<?php foreach ($news as $news_item): ?>

        <h3><?php echo $news_item['title']; ?></h3>
        <div class="main">
                <?php echo $news_item['text']; ?>
        </div>
        <p><a href="<?php echo site_url('news/'.$news_item['slug']); ?>">View article</a></p>

<?php endforeach; ?>

Instead of calling the get_new() method without a parameter, the $slug variable is passed, so it will return the specific new_table record data item. The only things left to do is create the corresponding view at application-package_folder/views/new_view.php. Put the following code in this file.
<?php
echo '<h2>'.$new_item['title'].'</h2>';
echo $new_item['text'];   

Routing

Because of the wildcard routing rule created earlier, you need an extra route to view the controller that you just made. Modify your routing file (application/config/routes.php) so it looks as follows. This makes sure the requests reaches the New_api controller instead of going directly to the Pages controller. The first line routes URI’s with a slug to the view() method in the New_api controller.
$route['new/(:any)'] = '<application_type_api_package_folder>/new_api/view/$1';
$route['new'] = '<application_type_api_package_folder>/new';
$route['(:any)'] = '<application_type_api_package_folder>/pages/view/$1';
$route['default_controller'] = '<application_type_api_package_folder>/pages/view';
Point your browser to your document root, followed by index.php/news and watch your news page.

Comments

  1. Infotrench is the best Codeigniter Development Company and provides the best services in Australia, UK, USA, Delhi, Noida, Gurugram, Ghaziabad, Faridabad. Contact us now!


    Codeigniter development company

    ReplyDelete

Post a Comment

Popular posts from this blog

Java Currency Formatter Solution

Given a  double-precision  number,  , denoting an amount of money, use the  NumberFormat  class'  getCurrencyInstance  method to convert   into the US, Indian, Chinese, and French currency formats. Then print the formatted values as follows: US: formattedPayment India: formattedPayment China: formattedPayment France: formattedPayment where   is   formatted according to the appropriate  Locale 's currency. Note:  India does not have a built-in Locale, so you must  construct one  where the language is  en  (i.e., English). Input Format A single double-precision number denoting  . Constraints Output Format On the first line, print  US: u  where   is   formatted for US currency.  On the second line, print  India: i  where   is   formatted for Indian currency.  On the third line...

Java Loops II print each element of our series as a single line of space-separated values.

We use the integers  ,  , and   to create the following series: You are given   queries in the form of  ,  , and  . For each query, print the series corresponding to the given  ,  , and   values as a single line of   space-separated integers. Input Format The first line contains an integer,  , denoting the number of queries.  Each line   of the   subsequent lines contains three space-separated integers describing the respective  ,  , and   values for that query. Constraints Output Format For each query, print the corresponding series on a new line. Each series must be printed in order as a single line of   space-separated integers. Sample Input 2 0 2 10 5 3 5 Sample Output 2 6 14 30 62 126 254 510 1022 2046 8 14 26 50 98 Explanation We have two queries: We use  ...

Java Static Initializer Block

Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks. It's time to test your knowledge of  Static initialization blocks . You can read about it  here. You are given a class  Solution  with a  main  method. Complete the given code so that it outputs the area of a parallelogram with breadth   and height  . You should read the variables from the standard input. If   or    , the output should be  "java.lang.Exception: Breadth and height must be positive"  without quotes. Input Format There are two lines of input. The first line contains  : the breadth of the parallelogram. The next line contains  : the height of the parallelogram. Constraints Output Format If both values are greater than zero, then the  main  method must output the area of the  parallelogram . Otherwise, pri...