(转载:) http://blog.kevingomez.fr/2012/12/18/storing-symfony2-sessions-in-memcached/
Storing Symfony2 sessions in memcached
- 18 décembre 2012 /
- Kévin G. /
- Dev', WebDev' /
- 2s commentaires
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
|
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%
}]
|
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
|
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
|
That’s it!