Tutorial: Writing a helper

This tutorial will guide you through the making of a helper. Helpers in Kohana are a bunch of related but not interdependent functions that generally aid you in your development. For example the array helper supplement php’s array functions, the form helper helps you write forms without all the fuzz. One function in a helper won’t affect other functions like they do in libraries. They do not depend on each other to work.

Now, let’s start writing the helper. I developed a request helper and I’ll show the complete helper at the end. For the moment we’re just going to implement an request::is_ajax() helper to determine if the current request is an ajax request.

First, place a file named request.php in your application/helpers directory. Notice how it’s all lowercase. The file at its very simplest looks like this.

class request_Core{}

Right now this helper doesn’t have any methods.

See how the name of the helpers is appended with _Core. It’s there to allow for transparent extension of helpers and libraries. If we want to extend the helper we would create a file MY_request.php in application/helpers and it would look like:

class request extends request_Core{}

Back to the original helper. We need to implement the is_ajax() method.

class request_Core{
    public static function is_ajax() 
    {
 	 return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) 
                   && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
    }
}

You’re done. In your controllers, models or views you can do

if(request::is_ajax())
{
echo 'ajax request, yah yah yah';
}

The complete request helper can be found on google code.

Leave a Comment