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 | |
---|---|
One of the most important view helpers you should use
extensively is |
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:
-
(because our vendor name is Acme)SYSTEM
/source/acme/Acme/View/Helper -
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:
-
Acme_View_Helper
-
Acme_App_Helper
-
Solar_View_Helper
For simplicity sake, we will use the default Acme_View_Helper.
Create a new folder called View
in the
folder.
SYSTEM
/source/acme/Acme
$cd
$SYSTEM
/source/acme/Acmemkdir View
Create another folder called Helper
in the
folder.
SYSTEM
/source/acme/Acme/View
$ 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.
<?php
/**
* 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) {
return;
}
// 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
view script and add the following to the bottom.
SYSTEM
/source/acme/Acme/App/Blog/View/index.php
<?php echo $this->phone('1235551212'); ?>
Save the file and view the blog home page. You should see
(123) 555-1212
printed at the bottom.