CI Basics Tutorial (Controllers, Views and Routing)

Why I Copy other People’s Writings

Read Fresh Start with CodeIgniter first. Otherwise, just keep in mind that after a fresh install the generic URL will load the welcome.php controller. This behavior won’t change until you modify $route['default_controller'] in routes.php.

Controller & URL Pattern

The first thing you’re going to do is set up a controller to handle static pages.

For example, when a call is made to:

http://example.com/news/latest/10

More likely it will be:
http://example.com/index.php/news/latest/10


We might imagine that there is a controller named “news”. The method being called on news would be “latest”. The news method’s job could be to grab 10 news items, and render them on the page. Very often in MVC, you’ll see URL patterns that match:

http://example.com/%5Bcontroller-class%5D/%5Bcontroller-method%5D/%5Barguments%5D

As URL schemes become more complex, this may change. But for now, this is all we will need to know.

Take a look at routes.php below. It’ll shed some light on this matter.

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
|	example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
|	http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There area two reserved routes:
|
|	$route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
|	$route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router what URI segments to use if those provided
| in the URL cannot be matched to a valid route.
|
*/

//$route['default_controller'] = "welcome";
//$route['404_override'] = '';
$route['default_controller'] = 'pages/view';
$route['(:any)'] = 'pages/view/$1';


/* End of file routes.php */
/* Location: ./application/config/routes.php */

Notice there is no closing PHP tag in the code above. As a matter of fact the NetBeans IDE for PHP sometimes opens up page templates which don’t have closing PHP tags. This is not a mistake. It’s a feature of PHP. The reason this feature was implemented in PHP relates to HTTP headers and white space. Do a Google search for: php opening and ending tag without closing. Here is quote from Chuck’s — Should you close that PHP tag?

…PHP allows you to omit the closing tag, and the Zend coding standard goes so far as to actually forbid closing this tag for PHP-only files.


We’ll get back to the News controller example in later posts; however, for the rest of this post we’ll be using Pages.


Create the Pages controller

Create a file at application/controllers/pages.php with the following code.

<?php

class Pages extends CI_Controller {

	public function view($page = 'home')
	{

	}
}

It is a thought provoking coincidence that this method was named view because within it will be a call to a different view method. More on this will follow.


Note: the CI_Controller class is located in 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.

This means Pages is an application—This application is just part of the CodeIgniter installation. So, one CI folder can hold many applications.

Create header and footer views

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.

A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer.

Create the header at application/views/templates/header.php and add the following code.

<html>
<head>
	<title><?php echo $title ?> - CodeIgniter 2 Tutorial</title>
</head>
<body>
	<h1>CodeIgniter 2 Tutorial</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:

<strong>&copy; 2011</strong>	
</body>
</html>

Adding logic to the controller

— and two main views —

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/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('application/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.

Notice the lack of code to terminate the script right after the show_404() statement. There is probably some code to handle that in the show_404() function.

The reason that the relative path parameter used in this example’s file_exists() function call works is that this Pages object is instantiated by index.php—which is located in the same directory as the application directory.

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.


I wish the author had explained the following code:

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

But, I figured it out! load is a property of the Pages object; load itself is an object — and view is load’s method.


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 (supplied by user) to any controller and method, and break free from the normal convention:

http://example.com/%5Bcontroller-class%5D/%5Bcontroller-method%5D/%5Barguments%5D

Using custom routing rules—which you define—you will be able to specify what the URI which the user specifies means to your CI installation (which simply expects a controller name, a method name and possibly one parameter.)

Edit routes.php

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 of equality statement) 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.

If your CI is configured to expect it then index.php must precede the controller and view specified by the user in the URI. If the user will only specify a parameter he must still precede it with with index.php as part of the URI. Only if the URI has nothing but the CI directory in it will the user not have to include index.php in it.

More information about routing can be found in the URI Routing documentation.

Here, the first rule in the $routes array matches any request which does not specify a controller, method and possible parameter. and runs the view() method of the pages class.

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!

Summary #1

What you want:

You want to create a static site.

You want
http://sameh-labibs-imac.local/CodeIgniter_2.1.0/index.php/pages/view/home
to take you to home page.

You want
http://sameh-labibs-imac.local/CodeIgniter_2.1.0/index.php/pages/view/about
to take you to about page.

You want
http://sameh-labibs-imac.local/CodeIgniter_2.1.0/
to take you to home page.

You want
http://sameh-labibs-imac.local/CodeIgniter_2.1.0/index.php
to also take you to home page.

You want
http://sameh-labibs-imac.local/CodeIgniter_2.1.0/index.php/home
to also take you to home page.

You want
http://sameh-labibs-imac.local/CodeIgniter_2.1.0/index.php/about
to take you to about page.

How to get it:

  1. index.php and Router run first.
    Those represent CI code which will run before your code runs.
  2. Create controller class called Pages at application/controllers/pages.php. Create one or more methods for this controller. For this example Pages has only one method — view. view takes a single argument ($page) defaulting to 'home'. Create header and footer views at application/views/templates/header.php and application/views/templates/footer.php as HTML with embedded PHP (which displays $title).
  3. Create home and about views at application/views/pages/home.php and application/views/pages/about.php as HTML with embedded PHP (which displays $title).
  4. Add logic to the controller—See code above.
  5. Implement custom routing rules so that (for example) when the user wants the URL
    http://sameh-labibs-imac.local/index.php/pages/view
    all they have to type-in is
    http://sameh-labibs-imac.local/index.php
    You do that by making routing configuration changes in the routing file:
    application/config/routes.php

Summary #2

  • Write a controller.
  • The controller can have one or more methods.
  • Routing allows the user to load pages by forming URLs which specify a controller, method, and (possibly) a data string.
  • Custom routing allows the user to shorten URLs.
  • The user supplied data string becomes an argument to be made use of by the user specified controller and method.
  • Within the controller’s method you set the variables to be passed to the view.

Summary #3

In this example we had a controller (Pages) for viewing (view) one of a bunch of static pages. It is possible to create — as another example — a controller called Maintenance with a method called add_part_stage_one.

Based on what I’ve learned so far I assume:

  • A website (www.gxsam11.net) can have multiple controllers (classes.)
  • Each controller is an application (Maintenance.)
  • Each application can have several sub-applications (methods—add_part_stage_one.)
  • Sub-apps (methods) can be used to present a static page, a dynamic page or a single form stage of a multi-stage form application.
  • Each URI passed from browser to server specifies a sub-app—and, results in a single page of output (view.) That page output will consist of the view being requested or a view explaining what went wrong.
  • The parameter specified in the URI is used by the sub application (method) to help specify the content of the view. Not all methods need or accept a parameter.
Advertisements

About samehramzylabib

See About on https://samehramzylabib.wordpress.com
This entry was posted in CodeIgniter and tagged , . Bookmark the permalink.

Comment

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