Using the TextHelper with CakePHP

U

Really, the TextHelper?  Yes, this is probably one of the most overlooked helpers in CakePHP.  Sure we all know about the HTML Helper, Form Helper, JS Helper, etc… but how many of us use the Text Helper?  I’ve seen so many custom functions for truncating text and adding an ellipsis (…) to the end of it.  How about replacing email addresses with links?  Etc…  No more I say!  Let’s begin explorining the Text Helper now.

First we begin by importing it in to our code.  Open a controller that controls your view:

[code]<?php

class MyController extends AppController {

var $helpers = array(‘Text’);

}

?>[/code]

Now, let’s open up our view and begin using it:

[code]Email: <?php echo $this->Text->autoLinkEmails($my_email);?><br/>

Website: <?php echo $this->Text->autoLinkUrls($my_url);?><br/>

Company Description:<br/>

<?php echo $this->Text->autoLink($my_desc);?>[/code]

Above are three different scenarios all doing very similar things.  The first example, will convert our normal email address into a “mailto” link allowing users one-click access to send an email.  The second example, will turn our website into a clickable link.  Finally, the third example will convert both an email and/or a URL into a link!

Now you don’t need to write crazy regular expressions looking for what might be the start of a link and the end of link; it’s already done for you.  Not only that, it has been well tested!

Next we have the “truncate” function.  Do you have a news listing where you want to show a brief description of the article?  See the sample below to help you get it done quickly:

[code]<h1>News</h1>

<?php foreach ($articles as $article):?>

<div>

<div><?php echo $article[‘title’];?></div>

<div>

<?php echo $this->Text->truncate($article[‘description’], 250, array(‘ending’ => ‘…’, ‘exact’ => false));?>

</div>

</div>

<?php endforeach;?>[/code]

Not done yet, the last example I want to touch upon is the toList function; another excellent time saver.  In this example, let’s assume that we have a user profile and we have them enter their interests in.  In today’s society this would most likely be done with some sort of auto complete functionality to avoid the user having typos and to speed things up.  We could then store a comma separated list of this interests in the users table.  Then when we want to display what the user is interested in, we use this handy function:

[code]Interests: <?php echo $this->Text->toList(explode(‘,’, $user[‘interests’]));?>[/code]

Our comma separated list remains the same, but CakePHP has automatically added “, and ” to our last interest automatically.

A few other great functions that I will allow you to explore further are the following:

– highlight

– excerpt

– stripLinks

Visit the Cookbook for full details: http://book.cakephp.org/view/1469/Text

Enjoy!

Other useful articles

About the author

By Jamie

My Books