using built-in helpers in CodeIgniter

In this tutorial, we will see how to use CI build-in helpers. For this example, we will use the URL helper for generating links. The URL helper file contains functions that assist in working with URLs. We will use the URL helper function site_url(), which returns the site URL as specified in the config file.

This example will be constructed from either of the following controllers:

  • application/controllers/ helperexample1.phpThis controller loads the built-in CI helper URL.
    $this->load->helper('url'); 
    

    The controller renders a view named helper-example1-view

  • application/views/helper-example1-view.phpThis view will use the URL helper to generate links in the view file

    Let us assume the URLs to the project root are as follows: http://mydomain.com/myproject. http://mydomain.com/myproject/helperexample1

    Tip

    The source code is provided with this book via URLs.

The controller file

Now we will see how the controller loads the built-in CI URL helper so the view file will be able to use the URL helper function site_url, which generates the links.

class Helperexample1 extends CI_Controller {
  /**
   * Index Page for this controller.
   *
   * Maps to the following URL
   *     http://example.com/index.php/welcome
   *  - or -  
   *     http://example.com/index.php/welcome/index
   *  - or -
   * Since this controller is set as the default controller in 
   * config/routes.php, it's displayed at http://example.com/
   *
   * So any other public methods not prefixed with an underscore
       *  will
   * map to /index.php/welcome/<method_name>
   * @see http://codeigniter.com/user_guide/general/urls.html
   */
    public function index()
    {
  	      	  // Loading the url helper
  	      	  $this->load->helper('url');
         $this->load->view('helper-example1-view');
    }
  }
/* End of file helperexample1.php */
/* Location: ./application/controllers/helperexample1 */

The view file

The view file calls the URL helper function site_url. Since the controller loaded the URL helper, it’s recognized by the view.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
  <title>Menu</title>
</head>
<body>
<table>
<tr>
<td><a href="<?php%20echo%20site_url('welcome');%20?>">Welcome</a></td>
</tr>
<tr>
<td><a href="<?php%20echo%20site_url('example2/more/1/2/3');%20%20%20%20%20%20?>">Example2</a></td>
</tr>
</table>
</body>
</html>
Recommended :  Clean up your code in laravel using model binding

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares