How to handle global variables from legacy codes in Symfony?
In Sympony, Use dependency injection to avoid global entirely.
1、Replace global $config with Symfony Parameters
# config/services.yaml
parameters:
db_host: '%env(DB_HOST)%' # Load from .env
app.some_value: 'foo' # Hardcoded value
Migrating Global Variables to Symfony (Best Practices)
When moving from a legacy PHP app with global variables to Symfony, you should avoid globals entirely and use Symfony’s dependency injection (DI) and configuration systems instead. Here’s how to handle common cases:
1. Replace global $configwith Symfony Parameters
Legacy Code (❌ Bad)
global $config;
$dbHost = $config['db_host'];
Symfony Way (✅ Good)
Step 1: Define Parameters
# config/services.yaml
parameters:
db_host: '%env(DB_HOST)%' # Load from .env
app.some_value: 'foo' # Hardcoded value
Step 2: Inject Parameters
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class DatabaseService
{
public function __construct(
private ParameterBagInterface $params
) {}
public function connect()
{
$dbHost = $this->params->get('db_host');
}
}
2、Replace global $db with a service
class DatabaseService
{
private \PDO $connection;
public function __construct(string $dsn)
{
$this->connection = new \PDO($dsn);
}
}
// Register in services.yaml:
services:
App\Service\DatabaseService:
arguments:
$dsn: 'mysql:host=%db_host%;dbname=%db_name%'
3、Replace global $user with Symfony Security
use Symfony\Bundle\SecurityBundle\Security;
class SomeService
{
public function __construct(
private Security $security
) {}
public function doSomething()
{
$user = $this->security->getUser(); // Typed to your User entity
$userId = $user->getId();
}
}
4、Replace global $loggerwith Monolog
use Psr\Log\LoggerInterface;
class PaymentService
{
public function __construct(
private LoggerInterface $logger
) {}
public function process()
{
$this->logger->info('Payment processed');
}
}
5、Replace define('CONSTANT', value)with Parameters or Enums
# config/services.yaml
parameters:
app.debug: '%env(bool:APP_DEBUG)%'
enum AppSettings: bool
{
case DEBUG = true;
}
if (AppSettings::DEBUG->value) { ... }
6、Replace Superglobals ($_SESSION, $_POST) with Symfony Request
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class FormController
{
public function submit(
Request $request,
SessionInterface $session
) {
$name = $request->request->get('name'); // $_POST
$session->set('user_id', 123); // $_SESSION
}
}
7、Replace require_once 'functions.php'with Services
class LegacyFunctionsService
{
public function doSomething()
{
// Replaces some_legacy_function()
}
}
class ModernService
{
public function __construct(
private LegacyFunctionsService $legacy
) {}
public function process()
{
$this->legacy->doSomething();
}
}

浙公网安备 33010602011771号