Learn how the helper methods work in Symfony 1.4 and how to implement them.

In Symfony 1.4 it's normal to reuse components and partials to include HTML blocks that require some extra logic. Other solution that many developers apply is the creation of classes with static methods, that work in the same way so to speak, however they have a prefix of a predefined class and they're always available. One feature that not every developer that support a legacy Symfony 1.4 project is the existence of Helper functions.

By default, Symfony 1.4 has a lot of helper functions available (almost) on the entire project e.g url_for, link_to etc. If you like this style, you need to know that you can create the same kind of helpers without writing the same function everywhere.

Creating and using helpers

To expose helpers globally on your project, you need to create the helper directory inside of yourproject/lib. Inside this folder you can create many helper files as you want that contains as many helper method as you want, the only condition is that the name of the file ends with *Helper, for example if you want to create helper functions that are related to manipulation of strings, we would create a file named StringHelpers.php inside the lib directory. There, instead of a class you should create plain PHP functions. For example, we'll include a method that highlights a given word inside a string HTML using spans:

<?php 
// application/lib/StringHelper.php

function highlight_word_inside_html($content, $search){
    if(is_array($search)){
        foreach ( $search as $word )
        {
            $content = str_ireplace($word, '<span class="highlight_word">'.$word.'</span>', $content);
        }
    } else {
        $content = str_ireplace($search, '<span class="highlight_word">'.$search.'</span>', $content);        
    }
    
    return $content;
}

Having this method, you can access to it (or them in case there are many inside your helper file) by including the helper using the use_helper method where you want to use it. For example, inside a view, you could simply do:

<?php use_helper('String') ?>

<!-- In your template -->
<?php 
    // Outputs: <p>Hello <span class="highlight_word">world</span></p>
    echo highlight_word_inside_html("<p>Hello world</p>", "world");
?>

As you can see, with helpers you are writing plain PHP methods so to speak and they can be used everywhere in your project. To learn more about the use_helper method of Symfony 1.4, please read the official legacy documentation.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors