9 cool Contao built-in functions | qzminski Blog

9 cool Contao built-in functions

Beside methods that are provided by various parts of the system, Contao also offers several additional functions that may improve your developer work. They solve common problems like standardizing a string or scanning a directory for files and folders.

Although these functions are not innovative, it is a good habit to use them, just to not reinvent the wheel again. Oh, and by the way – you can preview the /system/functions.php file at my pastebin.

Array functions

array_insert(&$arrCurrent, $intIndex, $arrNew)

You probably already used this function while configuring your own module. As its name says, it is used to insert either a new value or array into present one:

$arrOld = array('value_1', 'value_2', 'value_3');
$arrNew = array('value_new');

array_insert($arrOld, 1, $arrNew);

// Will result in:
Array
(
    [0] => value_1
    [1] => value_new
    [2] => value_2
    [3] => value_3
)

And an example of practical usage:

// Front end modules
array_insert($GLOBALS['FE_MOD']['miscellaneous'], 0, array
(
    'cd_collection' => 'ModuleCdCollection'
));

Note that this function does not return an array, but modifies existing one!

array_duplicate($arrStack, $intIndex)

This function duplicates the array element with a given index and puts it right under the duplicated item. For better explanation, take a look at this usage example:

$arrOld = array('value_1', 'value_2', 'value_3');
$arrNew = array_duplicate($arrOld, 1);

The $arrNew will be the following:

Array
(
   [0] => value_1
   [1] => value_2
   [2] => value_2
   [3] => value_3
)

Note that the key passed as second argument must be an integer!

String functions

specialchars($strString)

Because PHP in version lower than 5.2.3 does not support the fourth parameter (double_encode), there is a specialchars() function provided. It actually behaves the same as PHP’s htmlspecialchars(), but it makes sure that entities are never double converted.

This function is usually used when we display a text in the template:

$this->Template->title = specialchars('Foo & Bar > Foobar');

// Results in: Foo & Bar > Foobar

standardize($varValue)

Standardizing strings is a common practice all over the web – converted strings are mainly used in SEO friendly URLs. Contao uses this function to create the aliases of articles, news or calendar events:

// Generate alias if there is none
$strAlias = standardize('How do you do?');

echo $strAlias; // Prints: how-do-you-do

deserialize($varValue, $blnForceArray=false)

Well, the deserialize() function is just an alias for PHP’s unserialize(), with that exception you can force the passing value to be converted into array. The example of the function usage:

// Get data from database
$objNews = $this->Database->prepare("SELECT * FROM tl_news WHERE id=?")
           ->execute($intId);

// Put data into template
$this->Template->attachments = deserialize($objNews->enclosure);

The returned value is an array.

trimsplit($strPattern, $strString)

This function is very helpful when we need to parse a string e.g. that contains tags. User might enter the tags separated not only by commas, but also by whitespaces. We could use the PHP’s explode() function but that wouldn’t remove spaces. Therefore we can use trimsplit():

$strTags = 'foo, bar, foobar';
$arrTags = trimsplit(',', $strTags);

Notice that the first array items have an additional whitespace in front of them:

// explode()
Array
(
    [0] => foo
    [1] =>  bar
    [2] =>  foobar
)

// trimsplit()
Array
(
    [0] => foo
    [1] => bar
    [2] => foobar
)

ampersand($strString, $blnEncode=true)

As the “&” character is against a valid code, it is bad to put it on the website unencoded. Therefore Leo provides a small function that converts all these bad characters into their HTML entities (by default) or vice versa (if second argument is false).

$string = 'Foo & Bar';
echo ampersand($string); // Prints: Foo & Bar

When do we use it? Usually in the links or form’s action parameter:

// Links
$this->Template->nextLink = ampersand($strUrl);

// Form action
$this->Template->action = ampersand($this->Environment->request);

Miscellaneous

log_message($strMessage, $strLog=’error.log’)

Error logging might be helpful, but the biggest advantage is that it makes you a pr0 programmer. Contao provides a utility to save logs into custom files (or to /system/logs/error.log by default). It uses an error_log() function with second argument set to 3, which means that the “message is appended to the file destination. A newline is not automatically added to the end of the message string”.

Each message has the following format: [date time] message.

The usage example:

if ($this->Input->get('isAjax') !== '1')
{
    log_message('A performed request was not an AJAX. Request from IP: ' .
                 $this->Environment->ip());
    exit;
}

This  will result in entry added to file:

[26-Sep-2010 18:42:23] A performed request was not an AJAX. Request from IP: 127.0.0.1

scan($strFolder)

This little function scans the entire directory and returns all folders and files as an array. Unlike the PHP’s scandir(), it omittes the “.” and “..” pseudofolders. There’s also implemented a simple cache, so if the directory was already scanned, it will be read from cache.

If we would scan the tl_files directory, the output could be the following:

$arrFiles = scan(TL_ROOT . '/tl_files/'));
print_r($arrFiles);

// Output:
Array
(
    [0] => music_academy
    [1] => tiny_templates
    [2] => tinymce.css
)

About Author

Kamil Kuzminski

Hi! I'm a webdeveloper from Olsztyn, Poland. I'm the manager of Contao (fka TYPOlight) polish support website and community. I work mainly as a freelancer for private clients or various agencies.





Comments

  1. Ben September 29th

    Comment Arrow

    Wow, that is a great post Kamil! I just put standardize to use in a template I’m working on. Very helpful stuff!


  2. Lionel September 29th

    Comment Arrow

    Very interesting. Thx


  3. Brian October 8th

    Comment Arrow

    Big thanks from me also.


  4. Unearth October 10th

    Comment Arrow

    Great! This is the only thingi I’m missing in Contao, a reference of all the build in features with a little useful example and explanation how you’ve done it! Thx


  5. livelybrowsers October 19th

    Comment Arrow

    Thanks for good stuff


  6. aparadekto October 25th

    Comment Arrow

    Hey, I can’t view your site properly within Opera, I actually hope you look into fixing this.


Add Yours

  • Author Avatar

    YOU


Comment Arrow