5.5. Helpers

5.5.1. Introduction

Helpers are meant to provide functions that are commonly needed in controllers or views. Trex comes with an initial set of helper classes: Form, File, Security, String, Text and Uri.

Let’s say we want to load a helper named “File”. By default, the class is prefixed with “Trex_Helper_”, and the last segment of the class name is the helper name, this segment should be TitleCapped, the full class name is then: Trex_Helper_File. If the class doesn’t contain any methods it will still be included.

Only the “Trex_Helper_Default” class is loaded by default.

5.5.2. Loading Helper Files

The getHelper() method is in charge of loading the file and providing a singleton instance of the object, you only have to call this method and pass the name of the helper as a parameter. The parameter is always the file name of the helper, without the .php file extension.

  • obj getHelper ( string file_name )

5.5.3. Using Helpers

You can use helpers in your action controllers or view scripts. To use a helper in your view script, call it using $this->getHelper(name) and assign it to the Template instance. Behind the scenes, the Module will load the Helper class, create an object instance of it, and call its method. The object instance is persistent within the Module and Template instance, and is reused for all future calls to $this->getHelper(name).

Example:

app/modules/news/News.php

class News extends Trex_Module
{
        public function actionIndex()
        {
                // call the randomString() method of the Helper_String object
                $newPassword = $this->getHelper("String")->randomString();

                $template = $this->loadTemplate("index.html");

                // assign value
                $template->newPassword = $newPassword;

                // assign helper object to the Template instance
                $template->helperString = $this->getHelper("String");

                return $template;
        }
}

app/modules/news/views/frontend/index.html

<h1>Test Helper</h1>

    <p>New password assigned: <?php echo $this->newPassword; ?></p>
    <p>Generate new password: <?php echo $this->helperString->randomString(); ?></p>