You are currently browsing the archive for the symfony category.

The problem: make symfony use PHP’s default session behavior.
Symfony session handling is based on timed sessions – you set a time
after which the session will expire – but the default PHP behavior is to
expire when the user closes the browser window. This is also the most
commonly desired behavior for sessions. The drawback of using a timed
session is that it could expire while the user is still on the site.
This is an issue in LectureTools,
because students may sit for an hour or more without loading a new
page, and they may even have logged in before class. You can solve this
little problem easily if you are using symfony 1.1 (currently in beta).
Just set the timeout to false in settings.yml:

    timeout:    false

But if you are using the stable 1.0 branch of symfony, this will do just
the opposite – it will make your sessions time out immediately! To make
this work, we have to override sfBasicSecurityUser‘s initialize() method. I will describe two ways
to do this; one is a short hack, the other is longer and somewhat more proper.

Here’s the short way:

class myUser extends sfBasicSecurityUser
  public function initialize($context, $parameters = null)
    if (sfConfig::get('sf_timeout') == 0) {
      // session will expire if window is open for a day
      sfConfig::set('sf_timeout', 86400);

    return parent::initialize($context, $parameters);

This works because the sf_timeout setting is not used by
any other class (at the moment), so changing it doesn’t have any side
effects. If you set your timeout to 0 or false, symfony will always
think you have set the session timeout to 24 hours, but the session will
actually expire when the user closes the browser window.
If you are not comfortable with “hacks” like the above, you could copy the initialize() method from
sfBasicSecurityUser, change it in the appropriate place, and skip calling the parent constructor altogether.
Unfortunately, sfBasicSecurityUser calls its parent constructor, so you have to rewrite them both:

class myUser extends sfBasicSecurityUser
  public function initialize($context, $parameters = null)
    $this->context = $context;

    $this->parameterHolder = new sfParameterHolder();

    $this->attributeHolder = new sfParameterHolder(self::ATTRIBUTE_NAMESPACE);

    // read attributes from storage
    $attributes = $context->getStorage()->read(self::ATTRIBUTE_NAMESPACE);
    if (is_array($attributes))
      foreach ($attributes as $namespace => $values)
        $this->attributeHolder->add($values, $namespace);

    // set the user culture to sf_culture parameter if present in the request
    // otherwise
    //  - use the culture defined in the user session
    //  - use the default culture set in i18n.yml
    if (!($culture = $context->getRequest()->getParameter('sf_culture')))
      if (null === ($culture = $context->getStorage()->read(self::CULTURE_NAMESPACE)))
        $culture = sfConfig::get('sf_i18n_default_culture', 'en');


    // read data from storage
    $storage = $this->getContext()->getStorage();

    $this->authenticated = $storage->read(self::AUTH_NAMESPACE);
    $this->credentials   = $storage->read(self::CREDENTIAL_NAMESPACE);
    $this->lastRequest   = $storage->read(self::LAST_REQUEST_NAMESPACE);

    if ($this->authenticated == null)
      $this->authenticated = false;
      $this->credentials   = array();
      // Automatic logout logged in user if no request within [sf_timeout] setting
      if (0 != sfConfig::get('sf_timeout') && null !== $this->lastRequest && (time() -
$this->lastRequest) > sfConfig::get('sf_timeout'))
        if (sfConfig::get('sf_logging_enabled'))
          $this->getContext()->getLogger()->info('{sfUser} automatic user logout due to timeout');

    $this->lastRequest = time();


That should do it!

I have redone the sfPropelTestPlugin, and it is now sfModelTestPlugin, with support for Doctrine and Propel 1.3! Also new Рyou can now specify the test data file/directory at runtime, allowing for more flexibility with your tests. I want to thank Anders Betn̩r and my readers for bug reports and patches!

If you’ve ever tried to write a symfony unit test for a model class – or for any piece of code that interacts with the database – then you know what a headache it can be. sfPropelTestPlugin to the rescue! This plugin loads all the necessary symfony components for database interaction, and goes a step further: test data is automatically reloaded to the test database at the beginning of each test case, so you don’t have to worry about your tests interacting with each other. Here’s an example of a unit test written with sfPropelTestPlugin:

class myUnitTest extends sfPropelTest
  public function setup()
    $this->bob = UserPeer::retrieveByPK('bob');

  public function teardown()
    $this->diag('Test method complete!');

  public function test_user()
    $this->is($this->bob->getId(), 'bob', 'Bob exists!');

    $user = new User();

    $joe = UserPeer::getBy(UserPeer::USERNAME, 'joe');
    $this->isa_ok($joe, 'User', 'Joe exists!');

  public function test_dataDelete()
    $this->is($this->bob->getId(), 'bob', 'Bob still exists!');

    $joe = UserPeer::getBy(UserPeer::USERNAME, 'joe');
    $this->ok(!$joe, 'Joe no longer exists.');

$test = new myUnitTest();

If you’ve written tests in Ruby on Rails, the above should look familiar. If not, let’s go through the code:

The first two lines are setup: The first line tells symfony what application to test – in this case, “myApp” – and the second line includes the code we need to test against the database. Next we define our “test case” – a class that extends sfPropelTest, which is itself a child of lime_test. Every method that begins with “test_” will be called in turn, with our test data being reloaded between each call. Also, the setup() method, if defined, will be called immediately before each test method, and the teardown() method, if defined, will be called immediately after. The last two lines create a new instance of our test suite, and call its execute() method, which runs our tests.

There you have it – a quick and painless way to run unit tests in symfony. One less excuse for not writing them!

I have updated my plugin for doing model-based validation in symfony. The new plugin uses the Propel builders instead of behaviors, so it is now called sfPropelValidatePlugin instead of the former (unwieldy) name sfPropelValidateBehaviorPlugin. If you have not investigated the Propel builder classes, I suggest you give them a look. By overriding the default classes used to build your Propel object and peer classes, you can write your modifications directly into your model’s base classes. This is a much cleaner and more readable solution than using Propel behaviors, and you avoid the performance hit that behaviors incur.

The default Propel builders can be found in the symfony source in these places:


The classes these inherit from are buried. They can be found here:


Through Flash’s FileReference and FileReferenceList classes, you can create a powerful file uploader that allows the user to upload multiple files with a single form element. But beware: unless the user happens to be using IE, the upload will use a new browser session to upload the files. This means that if you require that a user be authenticated before uploading something (and you better be), the upload won’t work – the request will be forwarded to the login form, or to wherever your system forwards unauthorized requests. This is a maddening bug to track down, and there is nothing you can do to make Flash use the right session. The work around is to send the session cookie in the url and, on the server side, use that to override the new (and wrong) session cookie sent by Flash. Here’s how that works in symfony, although much of the following is useful for other languages or frameworks:

First, we have to tell our Flash component what the cookie is, so it can roll it into the URL. One solution would be to pass the session cookie as an argument in FlashVars, but then the user’s session cookie is sitting unencrypted in the HTML, leaving them vulnerable to cross-site request forgery. Better to use javascript to fetch the cookie, and then put it in FlashVars. If you are using ufo.js, the first argument to UFO.create() should look like this:

  movie: '/flash/uploader.swf',
  id: 'uploader',
  name: 'uploader',

  flashvars: 'cookie=' + document.cookie,

  // other options ...

Note that if you are dealing with multilple cookies, you will want to parse the output of document.cookie and send only the desired cookie.

Next, add the cookie to the URL in your ActionScript (this is for ActionScript 2.0):

var list:Array = myFileRefList.fileList;
var item:FileReference;
var url:String = _root.uploadURL + '?cookie=' + _root.cookie;

for (var i:Number = 0; i < list.length; i++) {
  item.upload (url);

That does it for the client side. Now, we need to tell PHP to use our cookie instead of the one the browser sent. This does the trick:

list($cookieName, $cookieValue) = str_split('=', $_GET['cookie']);



If you are using symfony, things are a little more complex. We need to call session_name() and session_id() before session_start(); looking at the symfony source code, we find that session_start() is called in sfSessionStorage::initialize(). So a simple solution is to extend the sfSessionStorage class:

class mySessionStorage extends sfSessionStorage
  public function initialize($context, $parameters = null)
    if ( /* whatever the condition is when we want to do this */ ) {
      if ($cookie = $context->getRequest()->getParameter('cookie')) {
        $name = 'symfony';
        preg_match('/^' . $name.'=(.*)$/', $cookie, $asMatch);
        $value = $asMatch[1];


    parent::initialize($context, $parameters);

Finally, tell symfony to use the mySessionStorage class by editting factories.yml:

    class: mySessionStorage
      session_name: symfony

And you're done! Clear your cache, and try it out. An easy way to check if it's working is to add the following line to the end of index.php (or frontend.php):

file_put_contents('testSessionOverwrite.txt', sfContext::getInstance()->getRequest()->getActionName());

Now try uploading a file. If the action name in testSessionOverwrite.txt is the action you're uploading to, you're golden. If instead it is the name of the action that authenticates users, you have a problem somewhere, and you get to have the enjoyable experience of debugging PHP without browser output. Remember to erase the debugging line from your front controller when you get everything working.

Next time, just make the users upload their damn files one-at-a-time...

« Older entries