Skip to content

Accessing the front-end sfI18N object from the back-end application

by Matthias Noback on March 17th, 2011

Sometimes you want to use the front-end application’s sfI18N object in the back-end application. Mainly because it has access to the front-end messages (they are placed in apps/frontend/i18n/[culture]/messages.xml). The most elegant way to accomplish this is by creating a method in your backendConfiguration class:

class backendConfiguration extends sfApplicationConfiguration
{
  /**
   * Get the I18N object for the given application and culture
   *
   * @param string $application
   * @param string $culture
   *
   * @return sfI18N
   */
  public function getI18N($application, $culture)
  {
    $current_application = sfContext::getInstance()->getConfiguration()->getApplication();

    sfContext::switchTo('frontend');

    $factories = sfFactoryConfigHandler::getConfiguration(ProjectConfiguration::getActive()->getConfigPaths('config/factories.yml'));
    $class  = $factories['i18n']['class'];

    $i18n = new $class(ProjectConfiguration::getActive(), null, $factories['i18n']['param']);
    $i18n->setCulture($culture);

    // load the message source (before switching back to the other application)
    $i18n->getMessageSource();

    sfContext::switchTo($current_application);

    return $i18n;
  }
}

You may of course add your own shortcut method for retrieving the sfI18N object for the frontend application, with the current culture. It is also important to make this method lazy loading and caching, so that the quite expensive code of loading the application configuration is not executed too often.

From → Configuration, I18N

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS