Helpers
Examples
In this part you will learn how to write your own custom helpers that perform what you want them to. All helpers are stored into includes/helpers by default. Let's change to that directory and create a helper by creating a file called MyHelper.php.
By now, your directory structure should look like this:
includes/
helpers/
Links.php
Template.php
MyHelper.php
Now, for the system to be able to load your helper dynamically (to be able to call Application::loadHelper on your helper), you need to name your helper class exactly as your helper's source file, adding the prefix _Helper. So, let's open the newly created file and create the class:
class MyHelper_Helper extends Helper
{
// the code for your helper will go here
}
Let's load this fresh helper into our main application. Go to a controller action of your choice (Default/Index is used for simplicity), and add the following line in it:
Application::loadHelper('MyHelper');
The helper is now ready for use. Now, let's say you want to use the DB library into this newly created helper. Suppose we want to fetch all people from a database table and return them. We'll add the following method to the helper:
public function getPeople()
{
return $this->libraries->DB->query('SELECT * FROM people');
}
Ok, notice that the loaded libraries are available into the helper via $this->libraries->library_alias. Let's load the DB library (from our Default/Index action, after Application::loadHelper('MyHelper') has been called):
Application::getHelper('MyHelper')->using('DB', $this->DB);
And that's about it. You can now go into your templates/Default/Index.html file and call $Helpers->MyHelper->getPeople(). You will get what you asked for.
Your basic helper is now finished. Just add your methods in it and call them from your controller.
Check out the using() helper's method. Its syntax is as follows:
$Helper_Instance->using('library_alias', $object_instance)
Your object will be available into your helper as:
$this->libraries->library_alias