Slim/3 to Slim/4 - Recommended way to handle settings and dependencies

I have a web site originally written as per the instructions in the Slim/3 user guide:

  1. Have settings and dependencies in a Pimple container.
  2. Pass the container as argument to App constructor.
  3. Define route handlers as class references ( Foo::class or Foo::class . ':action')
  4. Get container in route handler constructor.

I’m struggling to migrate it all to Slim/4. For a start, it seems that containers are no longer mandatory. I installed Pimple but I couldn’t make it work due to not being PSR-11 compliant out of the box. I thought perhaps it’d be easier to just install another PSR-11 container and tried PHP-DI but things were berserk because this other library has an entirely different syntax and relies on a lot of automagic features (autowiring bit me on the foot almost instantly).

I think it’s time to stop and think and get back to design board.

What’s the Slim/4 way to handle application settings (paths, configuration flags…) and helper libraries (session, loggers, database, etc.) that makes sense and matches my current flow?

1 Like

put a variable in your vhost file called Application Environment and set it to dev/test/prod

make a Settings class with members for all your settings and getters to access

class Settings
{
    const APP_KEYS_DEV          = 'DEVELOPMENT';
    const APP_KEYS_TEST         = 'TEST';
    const APP_KEYS_PROD         = 'PRODUCTION';
    const APP_KEYS              = [self::APP_KEYS_DEV, self::APP_KEYS_TEST, self::APP_KEYS_PROD];

    protected function loadEnvironmentConfiguration()
    {
        if (isset($_SERVER['APPLICATION_ENVIRONMENT']))
        {
            if(in_array($_SERVER['APPLICATION_ENVIRONMENT'], Settings::APP_KEYS))
            {
                $this->APPLICATION_ENVIRONMENT = $_SERVER['APPLICATION_ENVIRONMENT'];
            }
            else
            {
                $this->loadError('Invalid Server Configuration: Invalid Application Environment Definition');
            }
        }
        else
        {
            $this->loadError('Invalid Server Configuration: No Application Environment Defined');
        }

then just set them all in a switch statement

function loadApplicationConfiguration()
{
        switch($this->APPLICATION_ENVIRONMENT)
        {
            case self::APP_KEYS_PROD:
            {
                $this->DOMAIN                       = 'https://website.com/';
                break;
            }
            case self::APP_KEYS_DEV:
            {
                $this->DOMAIN                       = 'https://localhost/';
                break;
            }
...

i havent moved to slim 4 yet, ive just been using the default container and ive got a dependencies script i call from index where i load middleware and controllers, not too worried about it, it works