<?xml version="1.0" encoding="UTF-8" ?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
  <title>Latest snippets tagged symfony</title>
  <link rel="alternate" href="http://snippets.prendreuncafe.com/snippets/tagged/symfony/order_by/date"></link>
  <id>http://snippets.prendreuncafe.com/snippets/tagged/symfony/order_by/date</id>
  <updated>2008-05-26T15:34:00Z</updated>
  <author>
    <name>Symfony</name>
    <author_email>noreply@symfony-project.com</author_email>
  </author>
<entry>
  <title>[Symfony] Effacer partiellement le cache d'une application</title>
  <link href="http://snippets.prendreuncafe.com/snippet/94"></link>
  <updated>2008-05-26T15:34:00Z</updated>
  <id>94</id>
  <summary type="html">Toujours utile depuis un contexte d'application différent de celui visé :

[code=php]
sfToolkit::clearGlob(sfConfig::get('sf_cache_dir').'/frontend/*/all/*/templates/toto.cache');
[/code]</summary>
</entry>
<entry>
  <title>Cross apps url helper for symfony 1.0</title>
  <link href="http://snippets.prendreuncafe.com/snippet/92"></link>
  <updated>2008-05-15T15:50:14Z</updated>
  <id>92</id>
  <summary type="html">Here's a helper that allow to generate cross apps urls in symfony 1.0

[code=php]
/**
 * Generates cross-apps urls in symfony 1.0
 *
 * @param  string  the app we want to go to
 * @param  string  the route in the app. Must be valid
 * @param  array   the arguments required by the route. Optional
 * @return string
 */
function cross_app_url($app, $route, $args = null)
{
  $host = sfContext::getInstance()-&gt;getRequest()-&gt;getHost() ;
  $env = sfConfig::get('sf_environment');
  $appRoutingFile = SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.$app.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'routing.yml' ;
  $route = substr($route, 1, strlen($route)) ;
  if (file_exists($appRoutingFile))
  {
    $yml = sfYaml::load($appRoutingFile) ;
    $routeUrl = $yml[$route]['url'] ;
    if ($args)
    {
      foreach ($args as $k =&gt; $v)
      {
        $routeUrl = str_replace(':' . $k, $v, $routeUrl) ;
      }
    }
    if (strrpos($routeUrl, '*') == strlen($routeUrl) - 1)
    {
      $routeUrl = substr($routeUrl, 0, strlen($routeUrl) - 2) ;
    }
  }
  return sprintf('http://%s/%s/%s',
                 $host,
                 ($env == 'dev' ? $app . '_dev.php' : ($app != $main_app) ? $app : ''),
                 $routeUrl);
}
[/code]

Adapted from [here](http://www.symfony-project.org/forum/index.php/mv/msg/7460/31105/)</summary>
</entry>
<entry>
  <title>Symfony, trier aléatoirement les résultat avec Propel et MySQL</title>
  <link href="http://snippets.prendreuncafe.com/snippet/83"></link>
  <updated>2008-03-30T15:34:49Z</updated>
  <id>83</id>
  <summary type="html">Attention, cela ne fonctionnera probablement qu'avec MySQL :

[code php]
&lt;?php
$c = new criteria;
$c-&gt;addAscendingOrderByColumn('rand()');
$results = TotoPeer::doSelect($c);
[/code]</summary>
</entry>
<entry>
  <title>[Symfony 1.1 beta] Créer un test unitaire et initialiser Propel</title>
  <link href="http://snippets.prendreuncafe.com/snippet/79"></link>
  <updated>2008-03-19T17:27:18Z</updated>
  <id>79</id>
  <summary type="html">Depuis l'apparition du nouveau système de configuration de Symfony 1.1, voici un boostrap type pour vos tests unitaires nécessitant l'accès à l'environnement Propel :

[code php]
&lt;?php
require_once(dirname(__FILE__).'/../../config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('main', 'test', true);
include($configuration-&gt;getSymfonyLibDir().'/vendor/lime/lime.php');
sfContext::createInstance($configuration);
[/code]

Pensez cependant à remplacer `main` par le nom de votre application courante (par ex. `frontend`).</summary>
</entry>
<entry>
  <title>[Symfony] Utiliser sqlite pour stocker le cache des templates</title>
  <link href="http://snippets.prendreuncafe.com/snippet/77"></link>
  <updated>2008-03-17T16:21:01Z</updated>
  <id>77</id>
  <summary type="html">D'abord, s'assurer d'avoir le module `sqlite` de php5 chargé et activé :

[code]
$ sudo apt-get install php5-sqlite
$ sudo /etc/init.d/apache2 restart
[/code]

Dans le fichier `factories.yml` de l'application concernée :

[code yml]
  view_cache:
    class:                     sfSQLiteCache
    param:
      automaticCleaningFactor: 0
      database:                %SF_ROOT_DIR%/cache/cache.db
[/code]

Et voilà, maintenant les `symfony cc` se feront en un éclair.</summary>
</entry>
<entry>
  <title>[Symfony] Un validateur de date qu'il est bien</title>
  <link href="http://snippets.prendreuncafe.com/snippet/76"></link>
  <updated>2008-03-16T08:14:55Z</updated>
  <id>76</id>
  <summary type="html">Quelques fonctionnalités en plus par rapport à sfDateValidator (qu'il étend), notamment l'interdiction de date futures ou passées et l'évitement du traitement de la langue courante utilisateur (utile pour les formats de date figés).

[code php]
/**
 * Custom date validator
 *
 */
class myDateValidator extends sfDateValidator
{
  /**
   * Execute this validator.
   *
   * @param mixed A file or parameter value/array
   * @param error An error message reference
   *
   * @return bool true, if this validator executes successfully, otherwise false
   */
  public function execute(&amp;$value, &amp;$error)
  {
    $culture = $this-&gt;getContext()-&gt;getUser()-&gt;getCulture();

    // Validate the given date
    if ($this-&gt;getParameter('with_culture'))
    {
      $value1 = $this-&gt;getValidDate($value, $culture);
    }
    else
    {
      $value1 = strtotime($value);
    }

    if (!$value1 || -1 == $value1) // Before php 5.1, strtotime() returns -1 on fail
    {
      $error = $this-&gt;getParameter('date_error');
      return false;
    }

    // Is there a compare to do?
    $compareDateParam = $this-&gt;getParameter('compare');
    $compareDate = $this-&gt;getContext()-&gt;getRequest()-&gt;getParameter($compareDateParam);

    // If the compare date is given
    if ($compareDate)
    {
      $operator = trim($this-&gt;getParameter('operator', '=='), '\'&quot; ');
      $value2 = $this-&gt;getValidDate($compareDate, $culture);

      // If the check date is valid, compare it. Otherwise ignore the comparison
      if ($value2)
      {
        $valid = false;
        switch ($operator)
        {
          case '&gt;':
            $valid = $value1 &gt;  $value2;
            break;
          case '&gt;=':
            $valid = $value1 &gt;= $value2;
            break;
          case '==':
            $valid = $value1 == $value2;
            break;
          case '&lt;=':
            $valid = $value1 &lt;= $value2;
            break;
          case '&lt;':
            $valid = $value1 &lt;  $value2;
            break;

          default:
            throw new sfValidatorException(sprintf('Invalid date comparison operator &quot;%s&quot;', $operator));
        }

        if (!$valid)
        {
          $error = $this-&gt;getParameter('compare_error');

          return false;
        }
      }
    }

    if (!$this-&gt;getParameter('allow_future') &amp;&amp; $value1 &gt; time())
    {
      $error = $this-&gt;getParameter('future_error');
      return false;
    }

    if (!$this-&gt;getParameter('allow_past') &amp;&amp; $value1 &lt; time())
    {
      $error = $this-&gt;getParameter('past_error');
      return false;
    }

    return true;
  }

  /**
   * Initializes the validator.
   *
   * @param sfContext The current application context
   * @param array   An associative array of initialization parameters
   *
   * @return bool true, if initialization completes successfully, otherwise false
   */
  public function initialize($context, $parameters = null)
  {
    // Initialize parent
    parent::initialize($context, $parameters);

    // Set defaults
    $this-&gt;getParameterHolder()-&gt;set('with_culture', true);
    $this-&gt;getParameterHolder()-&gt;set('allow_future', true);
    $this-&gt;getParameterHolder()-&gt;set('future_error', 'Future dates not allowed');
    $this-&gt;getParameterHolder()-&gt;set('allow_past', true);
    $this-&gt;getParameterHolder()-&gt;set('past_error', 'Past dates not allowed');
    $this-&gt;getParameterHolder()-&gt;add($parameters);

    return true;
  }
}

[code]</summary>
</entry>
<entry>
  <title>[Symfony] [Validator] Valider une valeur en fonction d'une blacklist</title>
  <link href="http://snippets.prendreuncafe.com/snippet/73"></link>
  <updated>2008-01-13T12:11:16Z</updated>
  <id>73</id>
  <summary type="html">Pour s'assurer qu'une valeur saisie par un utilisateur dans un formulaire Symfony ne fait pas partie d'une liste de valeurs interdites, on peut utiliser le validateur suivant :

Fichier sfBlacklistValidator.class.php :

[code=php]
&lt;?php
class sfBlacklistValidator extends sfValidator
{

  public function initialize($context, $parameters = null)
  {
    // initialize parent
    parent::initialize($context);

    // set defaults
    $this-&gt;getParameterHolder()-&gt;set('blacklist_error', 'Value is not an allowed one');
    $this-&gt;getParameterHolder()-&gt;set('case_sensitive', false);
    $this-&gt;getParameterHolder()-&gt;set('trim', true);
    $this-&gt;getParameterHolder()-&gt;add($parameters);
    return true;
  }

  public function execute(&amp;$value, &amp;$error)
  {
    // Forbidden names
    $blacklist = $this-&gt;getParameter('blacklist');
    $casesensitive = $this-&gt;getParameter('case_sensitive');
    $trim = $this-&gt;getParameter('trim');
    
    if ($trim)
    {
      $value = trim($value);
    }
    
    if (is_array($blacklist) &amp;&amp; count($blacklist) &gt; 0)
    {
      if ($casesensitive)
      {
        $match = in_array($value, $blacklist);
      }
      else
      {
        $match = false;
        foreach ($blacklist as $item)
        {
          if (is_string($item) &amp;&amp; strtolower($item) == strtolower($value))
          {
            $match = true;
            break;
          }
        }
      }
      if ($match)
      {
        $error = $this-&gt;getParameterHolder()-&gt;get('blacklist_error');
        return false;
      }
    }
    
    return true;
  }
  
}
[/code]

Dans un fichier de validation yml:

[code=yaml]
fields:
  myfield:
    sfBlacklistValidator:
      blacklist:       [admin, contact, info, infos, commercial, tech, support, sales, partnership, webmaster, business, owner]
      case_sensitive:  no
      trim:            yes
      blacklist_error: The username you requested is not available
[/code]

Les options sont assez explicites, mais en voici tout de même le détail :

* blacklist: tableau de valeurs prohibées au format YAML
* case_sensitive: effectuer les comparaisons en tenant compte de la casse
* trim: inclure les espaces en début et fin de chaînes
* blacklist_error: Message d'erreur à afficher en cas de valeur blacklistée</summary>
</entry>
<entry>
  <title>[Symfony] [Propel] Afficher la dernière requête effectuée</title>
  <link href="http://snippets.prendreuncafe.com/snippet/72"></link>
  <updated>2007-12-10T15:56:12Z</updated>
  <id>72</id>
  <summary type="html">Pour afficher la dernière requête effectuée avec Propel :

[code=php]
echo Propel::getConnection()-&gt;getLastExecutedQuery();
[/code]

C'est tout con, hein ?</summary>
</entry>
<entry>
  <title>Gérer les libellés et tris d'un selectbox avec Propel et les helpers objets Symfony</title>
  <link href="http://snippets.prendreuncafe.com/snippet/71"></link>
  <updated>2007-11-21T16:40:15Z</updated>
  <id>71</id>
  <summary type="html">Pour gérer un joli combobox avec des valeurs textuelles représentatives choisies pour un objet Propel et éventuellement les trier, on peut faire :

[code=php]
&lt;?php echo object_select_tag($produit, 'getTypeProduitId', array (
 'related_class' =&gt; 'TypeProduit',   
 'peer_method'   =&gt; 'doSelectOrderByCode',
)) ?&gt;
[/code]

ou bien dans un generator.yml

[code=php]
fields:
  departement_id: 
    params: text_method=getNomCode  peer_method=doSelectOrderByCode
[/code]</summary>
</entry>
<entry>
  <title>[Symfony] Cacher simplement un fragment de code</title>
  <link href="http://snippets.prendreuncafe.com/snippet/56"></link>
  <updated>2007-02-11T09:25:21Z</updated>
  <id>56</id>
  <summary type="html">Cacher le résultat d'un processus coûteux pour 24h :

[code]
&lt;?php if (!cache('huge_process_of_the_death', 86400)): ?&gt;
  &lt;?php foreach ($stuff as $item): ?&gt;
    // Your amazingly huge iteration processes here
  &lt;?php endforeach; ?&gt;
  &lt;?php cache_save() ?&gt;
&lt;?php endif; ?&gt;
[/code]

Pour le cacher pour un utilisateur spécifique :

[code]
&lt;?php if (!cache('huge_process_of_the_death'.md5($user-&gt;getEmail()), 86400)): ?&gt;
  &lt;?php foreach ($stuff as $item): ?&gt;
    // Your amazingly huge iteration processes here
  &lt;?php endforeach; ?&gt;
  &lt;?php cache_save() ?&gt;
&lt;?php endif; ?&gt;
[/code]

On s'assure juste de prendre l'empreinte md5 d'un attribut unique dans la table associée ;)</summary>
</entry>
</feed>