When I published my post about using a single symfony application to serve multiple domains using a database to store the site-specific data, there was some people to complain about the extra query you get on each request. Right. Using a (cached) config file instead is not that hard as long as you use it only to match a domain name against a numeric id. Storing more site-specific data is a bit more problematic, but we will solve this in a later post.

And because I'm lazy, I won't re-write the entire article, just highlight the differences between the two methods, so you might as well read the database version if you did not already.

Now, first thing, the config file. We will create a simple project-wide config file: /config/app.yml:

all:
  paris.carshop: 1
  auckland.carshop: 2

Then we detect the site and add a generic sfConfig entry for it. This is done, as before, in /config/ProjectConfiguration.class.php. We will only change the detectSite() method to take advantage of the cached config information:

[php]
  public function detectSite(sfEvent $event)
  {
    sfConfig::add(array('site_id' => sfConfig::get('app_'.$_SERVER['HTTP_HOST'])));
  }

Easy heh ?

Now we just have to adapt the model classes to use this config entry. The CarTable::createQuery() method will look like:

[php]
/**
 * Creates a query, adding the site criteria automatically
 *
 * @return Doctrine_Query
 * @see Doctrine_Table::createQuery()
 */

public function createQuery($alias = '')
{
  $query = parent::createQuery($alias);
  $query->where('site_id = ?', sfConfig::get('site_id'));
  
  return $query;
}

The Car::save() method:

[php]
/**
 * Automatically populates the site_id field if necessary
 * 
 * @see sfDoctrineRecord::save()
 */

public function save(Doctrine_Connection $conn = null)
{
  if (empty($this->site_id))
  {
    $this->setSiteId(sfConfig::get('site_id'));
  }

  return parent::save();
}

And you're all set ! For the record, here are the other modified files from the last post:

config/doctrine/schema.yml:

Car:
  columns:
    site_id:      { type: integer }
    name:         { type: string(255) }
    description:  { type: clob }
    image:        { type: string(255) }

data/fixtures/ now contains only the Car fixtures:

Car:
  car_1:
    site_id: 1
    name: Peugeot 307
    description: Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  car_2:
    site_id: 1
    name: Renault Laguna
    description: Maecenas tortor nunc, aliquam et, ultrices id, ornare consectetur, mauris.
  car_3:
    site_id: 2
    name: Subaru Impreza
    description: Ut accumsan diam et orci. Sed sit amet neque ac diam rutrum iaculis.