Skip to content

Symfony Environments

Symfony has the concept of Environments which for the most part handle configuration differences

https://symfony.com/doc/current/configuration.html

Debug

Along with environments, there is also a global concept of "debug" - in any environemt, the application can be set to be in debug mode.

By default, this is the case in test and dev enviroments

Kernel

The place to get current environment and debug information is the Kernel

<?php
$kernel->getEnvironment();
$kernel->isDebug();

Environment Helper

Generally though, passing around the full Kernel object is overkill. Instead, we suggest you create an EnvironmentHelper which provides read only access to some Kernel properties

<?php

declare(strict_types=1);

namespace MyProject\Helper;

use Symfony\Component\HttpKernel\KernelInterface;

/**
 * A simple service to provide read only access to some Kernel parameters.
 */
final class EnvironmentHelper
{
    /**
     * @var string
     */
    private $environment;
    /**
     * @var bool
     */
    private $isDebug;
    /**
     * @var string
     */
    private $projectDir;

    public function __construct(KernelInterface $kernel)
    {
        $this->environment = $kernel->getEnvironment();
        $this->isDebug     = $kernel->isDebug();
        $this->projectDir  = $kernel->getProjectDir();
    }

    /**
     * The current environment, eg dev, prod, test
     *
     * @return string
     */
    public function getEnvironment(): string
    {
        return $this->environment;
    }

    /**
     * Are we currently in debug mode?
     *
     * @return bool
     */
    public function isDebug(): bool
    {
        return $this->isDebug;
    }

    /**
     * The project root directory, eg where the composer.json file is
     *
     * @return string
     */
    public function getProjectDir(): string
    {
        return $this->projectDir;
    }
}