Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ideacouture's avatar

Configuring session storage to use multiple memcached servers

When configuring session storage to use memcached I am looking to also be able to pass the sever configuration.

My issue is that I have multiple environments and each environment needs a specific set of servers to use. When specifying SESSION_DRIVER=memcached the configuration seems to come from cache.stores.memcached. Is it possible to configure the servers list separately when setting the session driver as memcached?

0 likes
4 replies
ideacouture's avatar
ideacouture
OP
Best Answer
Level 1

What I did was the following

First add a helpers file app/Http/helpers.php and add to your composer

    "autoload": {
    ...
        "files": [
            "app/Http/helpers.php"
        ]
    }

In app/Http/helpers.php

/**
 * Return the environment specific list of memcached servers
 */
function memcachedServers()
{
    if (env('APP_ENV') == 'local') {
        return [
            [
                'host' => '127.0.0.1', 'port' => 11211, 'weight' => 100,
            ],
        ];
    }

    if (env('APP_ENV') == 'development') {
        return [
            ['host' => '127.0.0.1', 'port' => 11211, 'weight' => 100],
            ['host' => '127.0.0.2', 'port' => 11211, 'weight' => 100],
        ];
    }

    if (env('APP_ENV') == 'production') {
        return [
            [
                'host' => '127.0.0.1', 'port' => 11211, 'weight' => 100,
            ],
        ];
    }

}

In config/cache.php

        'memcached' => [
            'driver'  => 'memcached',
            'servers' => memcachedServers()
        ],
harhoo's avatar

I think you're just re-inventing Laravel's environment system here.

Rather than do this, just create

config/local/cache.php config/production/cache.php etc

and then have

return array(
    'memcached' => array(
        array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 100),
    ), 
);

etc. in each one.

Please or to participate in this conversation.