Store Symfony Sessions in Database with Doctrine

Here is how you can store your sessions in a central database with Doctrine in symfony. If you are trying to do this with Propel, the check out my follow up post: Store Symfony Sessions in Database with Propel

Step1 – Create your sessions table

  1.  
  2. CREATE TABLE IF NOT EXISTS `sessions` (
  3. `sess_id` varchar(64) NOT NULL,
  4. `sess_data` text NOT NULL,
  5. `sess_time` int(11) NOT NULL,
  6. KEY `sess_id` (`sess_id`)
  7. ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Thanks to Andy from blog.t8d.de for pointing out that there needs to be an index on the ‘sess_id’ column. You’ll want to make sure that it’s there so that your queries don’t drag when you start getting thousands of records in your sessions table.

Step 2 – Edit /config/databases.yml

You need to make sure that you have a connection set up for the session database. So edit /config/databases.yml so it has something like the following:

  1. all:
  2.   sessions_db:
  3.     class:          sfDoctrineDatabase
  4.     param:
  5.       dsn:          mysql://my_user:my_password@localhost/my_sessions_db

Step 3 – Edit the app/config/factories.yml

You will need to let symfony know that you are going to be using the sfPDOSessionStorage class to handle your session storage, so edit /app/config/factories.yml:

  1.   storage:
  2.     class: sfPDOSessionStorage
  3.     param:
  4.       db_table: sessions           # Name of the table storing the sessions
  5.       database: sessions_db     # Name of the database connection to use

Finally, make sure to clear your cache and you should be all set!

Step 4 – Configure symfony session cleanup, etc. (update)

Andy, from blog.t8d.de posted some additional findings and links on their blog about some settings that you will want to change within symfony and your php.ini to make sure that your application is performing the proper session cleanup.

Check out:

  1. http://blog.t8d.de/2008/05/06/symfony-sessions-in-mysql-mit-doctrine/
  2. http://robrosenbaum.com/php/howto-disable-session-timeout-in-symfony/
  3. http://redotheweb.com/2008/02/01/database-session-handling-and-garbage-collector/

About marc

a Senior Software Engineer in Los Angeles, CA. He likes to receive comments :)