We built a simple to-do list application last week by implementing the CI basics we learnt in first part of this tutorial. Today, let’s go over some of the things that will allow you to customise and extend the CI framework for your specific needs.
Changing the default URL routing
As we have already seen, CI parses the URLs in the following format:
CI allows us to make such tweaks by allowing us to write our own routing rules. These rules are defined in application/config/routes.php file in an associative array called $route . The key of the associative array will define the URI to be matched, and its corresponding value will be the destination URI to which the request to be routed to. Apart from providing two wildcard types ":num" (matches only number) and ":any" (matches any character), CI also allows you to use regular expressions to define the URI to be matched.
For example, to achieve the routing we discussed above, we simply do:
Graceful error handling
CodeIgniter allows you to generate custom error messages, which calls specific error templates.
CodeIgniter automatically shows a 404 error message for a missing controller. But, for generating a custom 404 error message for a missing page internally, we can do that by calling:
If you want a more generic error message, you can use the show_error function for that. We can specify both the error message, and the HTTP status code when we call this function. For example,
Managing multiple applications
Although so far, we have used CI to handle just a single application, we can indeed have multiple applications using the same CI installation. To do this, we need to create a folder for each of our applications – currently our application resides within the "application" folder. So, say we have two applications called "app1" and "app2", we can structure the folders this way:
To achieve better performance, it’s important we use caching effectively. This is especially true for high traffic, content oriented websites. To reduce the strain on our server, CI allows us to serve a static version of a page. Caching can be enabled on a per-page basis. Once we have enabled caching for a page, the first time the page is loaded, a static version of the file will be stored in system/cache folder. On subsequent page refreshes, this static version of the page will be served.
To enable caching of a particular page, we simply call this function from a controller:
Benchmarking your application
If you are interested in measuring the performance of various parts of your application, CI’s benchmarking class will be handy. The benchmarking class is automatically loaded by CI. To calculate the elapsed time between two points, we simply do:
CodeIgniter provides various helper classes, some of which we used in our to-do list application. To extend (redefining existing methods or adding new methods) a helper class, we have to create a file in the application/helpers folder with the exact name of the existing helper class (in the system/helpers folder), but prefixing it with a "MY_". So for e.g., if we want to extend the URL helper class (which is named url_helper.php), we have to create a file named "MY_url_helper.php" in the application/helpers folder.
Once we have done that, we can add either new methods to the file, or redefine an existing method (by using the same function name and parameters), which will then over-ride the default method defined in the helper class.
Beyond CodeIgniter - Kohana framework
Although CodeIgniter is an extremely agile and light-weighted framework, CI’s support for PHP 4 means that quite a few "hacks" were used to make it work in PHP4. With the emergence of PHP5, many of these hacks (such as for auto loading of classes), have become unnecessary as PHP5 supports them cleanly, out of the box. Kohana, which began as a fork of CodeIgniter, is a PHP framework built exclusively for PHP5. It is also an entirely community driver project (unlike CodeIgniter, which is managed by EllisLab). If you don’t need support for PHP4, you really should take a look at Kohana. It’s very similar to CodeIgniter, and you should not have too much trouble finding your feet in it.
With that, we come to the end of our three part series on CodeIgniter. If there is something I have left out, or was unclear about, please do mention them in the comments.
Changing the default URL routing
As we have already seen, CI parses the URLs in the following format:
example.com/className/functionName/variable1/variable2While this suits most of the times, sometimes we might want to tweak CI to handle things different. With a reference to the blog example we saw in the first part, say, we want to display the entries of a blog by accessing a URL along the lines of "example.com/post/postID". Here, we actually want the "postID" to be parsed as a variable rather than a function name.
CI allows us to make such tweaks by allowing us to write our own routing rules. These rules are defined in application/config/routes.php file in an associative array called $route . The key of the associative array will define the URI to be matched, and its corresponding value will be the destination URI to which the request to be routed to. Apart from providing two wildcard types ":num" (matches only number) and ":any" (matches any character), CI also allows you to use regular expressions to define the URI to be matched.
For example, to achieve the routing we discussed above, we simply do:
$route['post/(:num)'] = "post/show_post/$1";The above rule routes any request to the URL "post/postID" (where postID is a number), to the standard CI URL "post/show_post/$1" where show_post is a function of the post controller class.
Graceful error handling
CodeIgniter allows you to generate custom error messages, which calls specific error templates.
CodeIgniter automatically shows a 404 error message for a missing controller. But, for generating a custom 404 error message for a missing page internally, we can do that by calling:
show_404('path_to_missing_page');One place where you might be needing this is when you are serving images via a controller that parses the image ID passed as a paramter and fetches it from a secure storage to display it. The template for the 404 error page is found in application/errors/error_404.php file.
If you want a more generic error message, you can use the show_error function for that. We can specify both the error message, and the HTTP status code when we call this function. For example,
show_error('Hey, this is a 500 error message!', 500);The template for this error message is found in application/errors/error_general.php file.
Managing multiple applications
Although so far, we have used CI to handle just a single application, we can indeed have multiple applications using the same CI installation. To do this, we need to create a folder for each of our applications – currently our application resides within the "application" folder. So, say we have two applications called "app1" and "app2", we can structure the folders this way:
path_to_codeigniter/app1/ path_to_codeigniter/app2/Copy the contents of the "application" folder (containing the views, controller, etc.) to these new folders. In addition, each of our application will need an "index.php" file that defines the path to the system and the application folders. So, we have to copy the "index.php" file from CI’s root folder to the app1 and app2 folders, and change the $system_folder and $application_folder variables to:
$system_folder = "../system"; $application_folder = "../app1";
// (use "../app2" for app2)Caching
To achieve better performance, it’s important we use caching effectively. This is especially true for high traffic, content oriented websites. To reduce the strain on our server, CI allows us to serve a static version of a page. Caching can be enabled on a per-page basis. Once we have enabled caching for a page, the first time the page is loaded, a static version of the file will be stored in system/cache folder. On subsequent page refreshes, this static version of the page will be served.
To enable caching of a particular page, we simply call this function from a controller:
$this->output->cache($num_minutes);$num_minutes defines how long (in minutes) we want the cached page to be served. The function can be called from anywhere within your controller. One the $num_minutes has expired, a new version of the cached page will be written to the cache.
Benchmarking your application
If you are interested in measuring the performance of various parts of your application, CI’s benchmarking class will be handy. The benchmarking class is automatically loaded by CI. To calculate the elapsed time between two points, we simply do:
$this->benchmark->mark('time_start');
// start timing //...all the code goes here... $this->benchmark->mark('time_end');
// end timing
echo $this->benchmark->
elapsed_time('time_start', 'time_end');
To find out the total elapsed time, we can use the same elapsed_time function without any parameters:
echo $this->benchmark->elapsed_time();
Extending CI’s helper classes
CodeIgniter provides various helper classes, some of which we used in our to-do list application. To extend (redefining existing methods or adding new methods) a helper class, we have to create a file in the application/helpers folder with the exact name of the existing helper class (in the system/helpers folder), but prefixing it with a "MY_". So for e.g., if we want to extend the URL helper class (which is named url_helper.php), we have to create a file named "MY_url_helper.php" in the application/helpers folder.
Once we have done that, we can add either new methods to the file, or redefine an existing method (by using the same function name and parameters), which will then over-ride the default method defined in the helper class.
Beyond CodeIgniter - Kohana framework
Although CodeIgniter is an extremely agile and light-weighted framework, CI’s support for PHP 4 means that quite a few "hacks" were used to make it work in PHP4. With the emergence of PHP5, many of these hacks (such as for auto loading of classes), have become unnecessary as PHP5 supports them cleanly, out of the box. Kohana, which began as a fork of CodeIgniter, is a PHP framework built exclusively for PHP5. It is also an entirely community driver project (unlike CodeIgniter, which is managed by EllisLab). If you don’t need support for PHP4, you really should take a look at Kohana. It’s very similar to CodeIgniter, and you should not have too much trouble finding your feet in it.
With that, we come to the end of our three part series on CodeIgniter. If there is something I have left out, or was unclear about, please do mention them in the comments.
No comments:
Post a Comment