Symfony, Vagrant and NFS

Author: Robin
Monday, June 23 2014

As a big fan of Vagrant, I decided to use it in my first Symfony project at Viva IT.

I created a Debian 7.5 box with PuPHPet for my Mac OS X host. After happily developing for a day, I came in the next day and could no longer log into my application. It completely stumped me as there seemed to be no clue as to what was causing the error, with no messages or logs.

When removing our custom AuthBundle firewall settings from security.yml, and instead using basic HTTP authentication, I was able to log in again — hinting that session cookies weren’t being created as they should be.

Looking at puphpet/config.yaml, it suddenly occurred to me that I’d set Vagrant to use NFS between login working and not working. In the past I’d use NFS successfully with other frameworks as it dramatically speeds up page loading times. So I’d thought nothing of the switch.

Changing the NFS flag to false and provisioning  the Vagrant box filled the login problem. However, Vagrant was now running the Symfony application painfully slow. I cam across a blog post by Benjamin Eberlei describing techniques for speeding up Symfony in Vagrant. In the article, he provides a couple of methods for Symfony’s AppKernel class that override the default directories for the cache and logs. With these in place, I decided to provision my Vagrant box with nfs: 'true'. The application was now responding at a decent speed of ~200ms and I could log in!

There are, however, a couple of caveats to this solution:

  1. Behat gets upset when it tries to access the newly-defined cache and log directories. To love this, the directories are only used in the dev environment and not the test environment.
  2. Developers who aren’t using Vagrant aren’t likely to come across this issue, and so their cache and log directories should be left as default. This can be achieved by setting a VAGRANT true environment in the config.yaml, and then checking for the environment in AppKernel.

These are modified methods that need to be added to Symfony’s AppKernel:

public function getCacheDir()
{
    if (in_array($this->environment, array('dev')) && !empty($_SERVER['VAGRANT'])) {
        return '/dev/shm/vivadesk/cache/' . $this->environment;
    }
    return parent::getCacheDir();
}

public function getLogDir()
{ 
    if (in_array($this->environment, array('dev')) && !empty($_SERVER['VAGRANT'])) {
        return '/dev/shm/vivadesk/logs';
    }
    return parent::getLogDir();
}
Updating Entities When an Insert Has a Duplicate Key in Doctrine ORM Running Behat in PHPStorm EAP through Vagrant