Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "request"

Browser culture detection

This filter use the accepted-languages browser setting to setup the user culture. The autodetection is run once by session.

This filter is sponsored by Dorigo consultants.

It check app.yml for accepted_languages setting in order to fit the available application locales.

It allow the use of sf_culture request parameter overide (this overide is avaible by default in symfony afaik). So you can use language changing links in your application.

It may be enhanced by a check of the really available locales but i don't know how it can be done.

To use this filter, create a file named SwitchLanguageFilter.class.php in lib/ or app/frontend/lib and fill it with this code and follow its documentation :

<?php
/**
 * Setup user culture from request
 * 
 * from http://www.symfony-project.com/snippets/snippet/80
 * Thanks to François Zaninotto
 * Thanks to Garfield-fr on #symfony-fr
 * 
 * Add the following lines in your app.yml to configure your application available languages.
 *   all:
 *     accepted:
 *       languages: [en, fr]
 * 
 * Then add this to your filters.yml
 * 
 *   # Filter that setup user culture
 *   mySwitchLanguageFilter:
 *     class: SwitchLanguageFilter
 * 
 * @package    SwitchLanguageFilter
 * @subpackage filter
 * @author     Pierre-Yves Landuré <py.landure@dorigo.fr>
 */
 
class SwitchLanguageFilter extends sfFilter
{
 
  /**
   * Check that the language is a valid application culture.
   * @param string $language The tested language code
   * @param string $default_language The default language code
   * 
   * @return string $language if no accepted languages is set,
   *                else $language if it is in accepted languages
   *                else $default_language
   */
  private function getAvailableCulture($language, $default_language = null)
  {
    $all_languages = sfConfig::get('app_accepted_languages', array());
 
    if(count($all_languages))
    {
      if(in_array($language, $all_languages)) // Test if language is available
      {
        return $language;
      }
      else // Else test if first part of language is available
      {
        $language_parts = explode('_', $language);
        if(count($language_parts))
        {
          if(in_array($language_parts[0], $all_languages))
          {
            return $language_parts[0];
          }
        }
      }
      return $default_language;
    }
 
    return $language;
  }
 
  /**
   * The filter call.
   */
  public function execute ($filterChain)
  {
    $context = $this->getContext();
    $user = $context->getUser();
 
    $default_culture = sfConfig::get('sf_i18n_default_culture');
    $selected_culture = $user->getCulture();
 
    if(!$user->getAttribute('sf_culture_autodetected', false))
    {
      $browser_languages = $context->getRequest()->getLanguages();
 
      foreach($browser_languages as $language)
      {
        $allowed_culture = $this->getAvailableCulture($language);
        if($allowed_culture)
        {
          $selected_culture = $allowed_culture;
          break;
        }
      }
 
      $user->setAttribute('sf_culture_autodetected', true);
    }
 
    $selected_culture = $context->getRequest()->getParameter('sf_culture', $selected_culture);
    $selected_culture = $this->getAvailableCulture($selected_culture, $default_culture);
    if($selected_culture != $user->getCulture())
    {
      // The user wants to see the page in another language
      $user->setCulture($selected_culture);
    }
 
    $filterChain->execute();
  }
}
 
by Pierre-Yves Landuré on 2007-10-09, tagged culture  filter  i18n  request 

Get all request parameters from a template

This shortcut is useful to get in an array the module, action and request parameters from any templates.

$tab = array();
$tab = $this->getRequest()->getParameterHolder()->getAll();

:)

by julien levasseur on 2007-07-21, tagged parameters  request 

Copy request data into the session

Recently I needed to copy data that comes from a webform into the current session. Here is my solution ...

class myUser extends sfBasicSecurityUser {
    /**
     * Copy request data into the users session object
     *
     * @param array $exclude Fieldnames to exclude from copy
     */
    public function copyRequestData ($exclude = array ()) {
        /// Get the request instance and its currently posted fieldnames
        $req = sfContext::getInstance ()->getRequest ();
        $fieldNames = $req->getParameterHolder ()->getNames ();
 
        /// Always exclude "posted" module and action
        $exclude[] = 'module';
        $exclude[] = 'action';
 
        /// Evaluate each fieldname and do a "lookup" if it can
        /// be copied
        foreach ($fieldNames as $fieldName) {
            if (!in_array ($fieldName, $exclude)) {
                $this->setAttribute ($fieldName, 
                    $req->getParameter ($fieldName, null));
            } // end if
        } // end foreach
    }
}
by Eric Bartels on 2006-11-27, tagged copy  request  session  user 

Flash and Request parameters outside of an action

I don't know about you, but I often farm out action logic--like building a datastructure to pass to a template--to static functions in a class in my application or module lib/ directory.

However, these functions don't typically have access to the shortcut methods for setting/getting flash and request parameters (etc.). Like:

$foo = $this->getRequestParameter('foo');

Unless I've missed something, the code to do something similar outside of an action is just a little messy, and quite repetitive if used more than once. So I add a few things to my project to make the job simpler.

/**
 * This class adds a few more useful functions to the sfUser instance
 */
class myBasicUser extends sfBasicSecurityUser
{
    const FLASH_NAMESPACE = 'symfony/flash';
 
    /** User flash parameters (stored in the session until the next request) */
    public function setFlash($name, $value)
    {
        $this->setAttribute($name, $value, self::FLASH_NAMESPACE);
    }
 
    public function getFlash($name, $default = null)
    {
        return $this->getAttribute($name, $default, self::FLASH_NAMESPACE);
    }
 
    public function hasFlash($name)
    {
        return $this->hasAttribute($name, self::FLASH_NAMESPACE);
    }
 
    /** User attribute parameters (stored in the session until removed) */
    public function removeAttribute($name, $ns = null)
    {
        $this->getAttributeHolder()->remove($name, $ns);
    }
 
    public function getAttributes($ns = null)
    {
        return $this->getAttributeHolder()->getAll($ns);
    }
 
    public function removeAttributes($ns = null)
    {
        $this->getAttributeHolder()->removeNamespace($ns);
    }
 
    /** User parameter parameters (erased after every request) */
    public function removeParameter($name, $ns = null)
    {
        $this->getParameterHolder()->remove($name, $ns);
    }
 
    public function getParameters($ns = null)
    {
        return $this->getParameterHolder()->getAll($ns);
    }
 
    public function removeParameters($ns = null)
    {
        $this->getParameterHolder()->removeNamespace($ns);
    }
}
 
class myUser extends myBasicUser
{
//...
}

*Note: add those files to your lib/ director as myBasicUser.class.php and myUser.class.php respectively.

That gives me an easy way to do some things with the user object, but now I need an easy way to get the user outside of an action and an easier way to get/set request parameters/attributes, etc. I defined a class in my application lib/ directory like this:

/**
 * Shortcuts to all request and user attribute setting/getting/has functions
 * This class simply makes repetitive tasks a few characters (and in some cases, lines) shorter to accomplish
 */
class myTools
{
    /** Get context singleton */
    public static function getContext()
    {
        return sfContext::getInstance();
    }
 
    /** Get request singleton */
    public static function getRequest()
    {
        return sfContext::getInstance()->getRequest();
    }
 
    /** Request parameter holder */
    public static function getRequestParameterHolder()
    {
        return sfContext::getInstance()->getRequest()->getParameterHolder();
    }
 
    /** Request attribute holder */
    public static function getRequestAttributeHolder()
    {
        return sfContext::getInstance()->getRequest()->getAttributeHolder();
    }
 
    /** Request parameters (read-only) */
    public static function getRequestParameter($name, $default = null)
    {
        return sfContext::getInstance()->getRequest()->getParameter($name, $default);
    }
 
    public static function hasRequestParameter($name)
    {
        return sfContext::getInstance()->getRequest()->hasParameter($name);
    }
 
    /** Request attributes (read/write - erased after every request) */
    public static function getRequestAttribute($name, $default = null)
    {
        return sfContext::getInstance()->getRequest()->getAttribute($name, $default);
    }
 
    public static function setRequestAttribute($name, $value)
    {
        sfContext::getInstance()->getRequest()->setAttribute($name, $value);
    }
 
    public static function hasRequestAttribute($name)
    {
        return sfContext::getInstance()->getRequest()->hasAttribute($name);
    }
 
    /** Get user singleton */
    public static function getUser()
    {
        return sfContext::getInstance()->getUser();
    }
 
    /** User attribute holder */
    public static function getAttributeHolder()
    {
        return sfContext::getInstance()->getUser()->getAttributeHolder();
    }
 
    /** User parameter holder */
    public static function getParameterHolder()
    {
        return sfContext::getInstance()->getUser()->getParameterHolder();
    }
 
    /** User flash parameters (stored in the session until the next request) */
    public static function setFlash($name, $value)
    {
        sfContext::getInstance()->getUser()->setFlash($name, $value);
    }
 
    public static function getFlash($name)
    {
        return sfContext::getInstance()->getUser()->getFlash($name);
    }
 
    public static function hasFlash($name)
    {
        return sfContext::getInstance()->getUser()->hasFlash($name);
    }
 
    /** User attribute parameters (stored in the session until removed) */
    public static function getAttribute($name, $default = null, $ns = null)
    {
        return sfContext::getInstance()->getUser()->getAttribute($name, $default, $ns);
    }
 
    public static function setAttribute($name, $value, $ns = null)
    {
        sfContext::getInstance()->getUser()->setAttribute($name, $value, $ns);
    }
 
    public static function removeAttribute($name, $ns = null)
    {
        sfContext::getInstance()->getUser()->removeAttribute($name, $ns);
    }
 
    public static function getAttributes($ns = null)
    {
        return sfContext::getInstance()->getUser()->getAttributes($ns);
    }
 
    public static function removeAttributes($ns = null)
    {
        sfContext::getInstance()->getUser()->removeAttributes($ns);
    }
 
    /** User parameter parameters (erased after every request) */
    public static function getParameter($name, $default = null, $ns = null)
    {
        return sfContext::getInstance()->getUser()->getParameter($name, $default, $ns);
    }
 
    public static function setParameter($name, $value, $ns = null)
    {
        sfContext::getInstance()->getUser()->setParameter($name, $value, $ns);
    }
 
    public static function removeParameter($name, $ns = null)
    {
        sfContext::getInstance()->getUser()->removeParameter($name, $ns);
    }
 
    public static function getParameters($ns = null)
    {
        return sfContext::getInstance()->getUser()->getParameters($ns);
    }
 
    public static function removeParameters($ns = null)
    {
        sfContext::getInstance()->getUser()->removeParameters($ns);
    }
 
    /** User credentials */
    public static function clearCredentials()
    {
        sfContext::getInstance()->getUser()->clearCredentials();
    }
 
    public static function listCredentials()
    {
        return sfContext::getInstance()->getUser()->listCredentials();
    }
 
    public static function removeCredential($credential)
    {
        sfContext::getInstance()->getUser()->removeCredential($credential);
    }
 
    public static function addCredential($credential)
    {
        sfContext::getInstance()->getUser()->addCredential($credential);
    }
 
    public static function addCredentials()
    {
        sfContext::getInstance()->getUser()->addCredentials(func_get_args());
    }
 
    public static function hasCredential($credential)
    {
        return sfContext::getInstance()->getUser()->hasCredential($credential);
    }
 
    /** User authentication */
    public static function isAuthenticated()
    {
        return sfContext::getInstance()->getUser()->isAuthenticated();
    }
 
    public static function setAuthenticated($authenticated)
    {
        sfContext::getInstance()->getUser()->setAuthenticated($authenticated);
    }
 
    /** User culture */
    public static function setCulture($culture)
    {
        sfContext::getInstance()->getUser()->setCulture($culture);
    }
 
    public static function getCulture()
    {
        return sfContext::getInstance()->getUser()->getCulture();
    }
}

There you have it. Now it's as simple as...

class myModuleLib
{
  public static function myFunc()
  {
    ...
    $foo = myTools::getRequestParameter('foo', 'default_value');
    myTools::setFlash($foo);
    ...
  }
}

Overkill...? Maybe. You may use any of these functions that are useful, and simply omit those you think are unnecessary. The goal here is to standardize (even more) the methods used to access attributes of the request and user, etc. I'm guessing this will be beneficial for beginners (if nothing else, as an example), and also for people (like me) who like ridiculously consistent code.

Any comments, including comments on naming conventions of the functions are appreciated.

by Stephen Riesenberg on 2006-11-19, tagged action  attributes  module  parameters  request  session  user 
(3 comments)

Detect an Ajax request

A simple way to detect an ajax request.

In your action class.

$this->isAjaxCall = $this->getRequest()->isXmlHttpRequest();
 

I put the above line in my preExecute where needed, this way the variable is accessible by action and views.

Inside a template you can use the following as well:

$sf_request->isXmlHttpRequest()
 
by Fuad Arafa on 2006-10-27, tagged ajax  http  request 
(2 comments)