Archives pour 'symfony 1.2'

Liens inter-applications avec Symfony 1.2

10 novembre 2008

Après une première tentative peu concluante, voici un autre helper permettant de faire des liens entre différentes applications dans Symfony 1.2.

<?php
/**
 * @author Olivier Mansour
 */
 
/**
 * return an url for a given symfony application and an internal url
 *
 * @author Olivier Mansour
 *
 * @param string $appname
 * @param string $url
 * @param boolean $absolute
 * @param string $env
 * @param boolean $debug
 * @return string
 */
function cross_app_url_for($appname, $url, $absolute = 'false', $env = null, $debug = 'false')
{
 
  $initial_app = sfContext::getInstance()->getConfiguration()->getApplication();
  $initial_web_controler = basename(sfContext::getInstance()->getRequest()->getScriptName());
  // get the environment
  if (is_null($env))
  {
    $env = sfContext::getInstance()->getConfiguration()->getEnvironment();
  }
 
  // context creation
  if (!sfContext::hasInstance($appname))
  {
    $context = sfContext::createInstance(ProjectConfiguration::getApplicationConfiguration($appname, $env, $debug), $appname);
  }
  else
  {
    $context = sfContext::getInstance($appname);
  }
  $web_url = $context->getController()->genUrl($url, $absolute);
  sfContext::switchTo($initial_app); // usefull ?
  unset($context);
 
  //remove initial web controler
  // genUrl use $this->context->getRequest()->getScriptName();, its a call to $_SERVER
  // so I need this (sort of) hack
  $script_name = $appname;
  if (($env != 'prod') and $env)
  {
    $script_name.='_'.$env;
  }
  $script_name.='.php';
  // check if this file exist
  if (!file_exists(sfConfig::get('sf_web_dir').DIRECTORY_SEPARATOR.$script_name))
    throw new sfException('can t find '.$script_name.' in the web directory');
  $web_url = str_replace ($initial_web_controler, $script_name, $web_url);
 
  return $web_url;
}

Pour l’utiliser, c’est à peu près comme url_for :

<?php echo cross_app_url_for('front' , 'module/action?id=5&tmp=ok#raoul'); ?>
<?php echo cross_app_url_for('front' , '@route'); ?>

Jusqu’ici ça marche (Symfony 1.2 est en cours de développement, l’API peut encore un peu changer, attention) ! N’hésitez pas à mettre un commentaire si vous avez un retour.