5.5. View Helpers

There are many view helpers available in Solar. This chapter and chapter one introduced you to a few of them, such as Solar_View_Helper_Head, Solar_View_Helper_GetText, Solar_View_Helper_GetTextRaw, Solar_View_Helper_Escape, and Solar_View_Helper_Action. The best place to learn about each helper available to Solar is the API documentation: http://solarphp.com/package/Solar_View_Helper.

[Note] Note

One of the most important view helpers you should use extensively is Solar_View_Helper_Escape.

Additionally, Solar makes it easy to write your own helpers. Let's write our own helper that formats a 10 digit number into a standard formatted phone number. We want to go from 1235551212 to (123) 555-1212.

First, we need a location for our new helper. By default, Solar expects to find view helpers in two places:

  1. SYSTEM/source/acme/Acme/View/Helper (because our vendor name is Acme)

  2. SYSTEM/source/solar/Solar/View/Helper

Additionally, you can add locations to the class stack where Solar looks for helpers by editing the config file. For example, adding the following to SYSTEM/config.php

$config['Solar_View']['helper_class'] = array('Acme_App_Helper');

would change the class stack to this:

  1. Acme_View_Helper

  2. Acme_App_Helper

  3. Solar_View_Helper

For simplicity sake, we will use the default Acme_View_Helper.

Create a new folder called View in the SYSTEM/source/acme/Acme folder.

$ cd SYSTEM/source/acme/Acme
$ mkdir View

Create another folder called Helper in the SYSTEM/source/acme/Acme/View folder.

$ mkdir Helper

Change to the Helper directory and create a file called Phone.php.

$ cd Helper
$ vim Phone.php

Add the following code the the Phone.php file and save.

 * View helper to take a 10 digit number and 
 * convert to (###) ###-####
class Acme_View_Helper_Phone extends Solar_View_Helper {
    * Returns a formatted phone number.
    * @param string|int $number Unformatted number
    * @return string The formatted number
    public function phone($number=null)
        if (! $number) {
        // Add your own validation logic here
        $code = substr($number, 0, 3);
        $prefix = substr($number, 3, 3);
        $line = substr($number, 6, 4);
        return $this->_view->escape("($code) $prefix-$line");

Now let's test it and see if it works. Keep in mind that this helper has no validation logic.

Open the SYSTEM/source/acme/Acme/App/Blog/View/index.php view script and add the following to the bottom.

<?php echo $this->phone('1235551212'); ?>

Save the file and view the blog home page. You should see (123) 555-1212 printed at the bottom.