Storing Symfony2 sessions in memcached

(转载:) http://blog.kevingomez.fr/2012/12/18/storing-symfony2-sessions-in-memcached/

Storing Symfony2 sessions in memcached

Even if the only example in Symfony cookbook is about storing sessions with PDO, adapting it to memcached is pretty straightforward.

Memcached installation

If it’s not already done, install the following packages (supposing you are on a Debian-like system) :

1
aptitude install memcached php5-memcached
view raw gistfile1.txt  hosted with ❤ by   GitHub

This will install a memcached server and the PHP extension to use it. The server should e running on localhost, port 11211.
Just to be sure, check that the php extension has been enabled.

Modifying the session handler

Now, we’ll update our configuration to make our app use memcache to store sessions. To do that, we’ll use the MemcachedSessionHandler provided in the HttpFoundation bundle. As he need a \Memcached instance to work (and chat with our memcached server), we’ll use services to build the whole thing.

1234567891011
services :
session.memcached :
class : Memcached
arguments :
persistent_id : % session_memcached_prefix%
calls :
- [ addServer , [ % session_memcached_host% , % session_memcached_port% ]]
 
session.handler.memcached :
class : Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler
arguments : [ @ session.memcached , { prefix : % session_memcached_prefix% , expiretime : % session_memcached_expire% }]
view raw session_services.yml  hosted with ❤ by   GitHub

As usual, the configuration variables are stored in the parameters.yml file. Considering how simple they are, I won’t explain them but don’t hesitate to read   memcached’s documentation  if they are not clear enough.
1234567
parameters :
# ...
 
session_memcached_host : localhost
session_memcached_port : 11211
session_memcached_prefix : sess
session_memcached_expire : 3600
view raw parameters.yml  hosted with ❤ by   GitHub

Once we are done configuring our services, we just have to tell our application to use the service we just created.
123456789
imports :
# ....
- { resource : services/session.yml }
 
 
framework :
# ....
session :
handler_id : session.handler.memcached
view raw config.yml  hosted with ❤ by   GitHub

That’s it!

你可能感兴趣的:(memcached)