Code snippets for symfony 1.x

Navigation

use helpers from an action

technically this breaks MVC separation. but it can be handy (for formating data being stored to a database from an action, for example. This is most easily accomplished by copying the use_helper code to a custom class.

create a custom class in project\lib (or app\lib). i'll use Misc.class.php.

<?php
 
class Misc
{
    public static function use_helper($helperName)
    {
      static $loaded = array();
      if (isset($loaded[$helperName]))
      {
        return;
      }
 
      if (is_readable(sfConfig::get('sf_symfony_lib_dir').'/helper/'.$helperName.'Helper.php'))
      {
        // global helper
        include_once(sfConfig::get('sf_symfony_lib_dir').'/helper/'.$helperName.'Helper.php');
      }
      else if (is_readable(sfConfig::get('sf_app_module_dir').'/'.sfContext::getInstance()->getModuleName().'/'.sfConfig::get('sf_app_module_lib_dir_name').'/helper/'.$helperName.'Helper.php'))
      {
        // current module helper
        include_once(sfConfig::get('sf_app_module_dir').'/'.sfContext::getInstance()->getModuleName().'/'.sfConfig::get('sf_app_module_lib_dir_name').'/helper/'.$helperName.'Helper.php');
      }
      else
      {
        // helper in include_path
        include_once('helper/'.$helperName.'Helper.php');
      }
      $loaded[$helperName] = true;
    }
}

(clear your cache after adding a custom class, of course).

now to use a helper from an action:

Misc::use_helper('Date');
....
by hansbricks on 2006-08-02, tagged action  helper 

Comments on this snippet

gravatar icon
#1 Olivier Verdier on 2006-08-03 at 08:23

What about that solution:

include_once('symfony/helper/HelperHelper.php');
use_helpers('First', 'Second');

It would work as well, wouldn't it?

gravatar icon
#2 Olivier Verdier on 2006-08-03 at 04:06

Oh! Actually it is written in the post above: this is a copy-paste of the use_helper function. Huh? What is the point of copying an existing function??? The function is already there, it exists, just load it using include_once and there you go. So i'm afraid this snippet has no interest at all.

gravatar icon
#3 brikou on 2006-09-09 at 02:06

If you use include_once ('symfony/helper/HelperHelper.php');, you will have problem because later, symfony will try to reload it. So, instead use:

{{{ sfLoader::loadHelpers(array('First', 'Second')); }}}

(according to fabien)

gravatar icon
#4 Francois Zaninotto on 2006-09-11 at 03:37

brikou: this is with symfony > 0.8. For previous versions, the include_once() is the only solution.