Reputation:
I am using The DependencyInjection Component of Symfony 4 and I am trying to define the configuration settings (in config/services.yml
) for creating a simple ServerRequest
object. ServerRequest
receives the $_SERVER
variable (array) as argument for the constructor parameter $serverParams
.
It should print the array, but, instead, it prints the string "$_SERVER":
Hello from ServerRequest!
...path-to-project-root/mytests/ServerRequest.php:14:string '$_SERVER' (length=8)
Maybe you have an idea? Thank you very much!
parameters:
services:
_defaults:
autowire: false
autoconfigure: true
public: true
MyTests\ServerRequest:
arguments:
$serverParams: $_SERVER
<?php
namespace MyTests;
class ServerRequest {
private $serverParams;
public function __construct($serverParams) {
$this->serverParams = $serverParams;
echo 'Hello from ServerRequest!<br/>';
var_dump($this->serverParams);
}
}
<?php
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
/*
* Include the Composer autoloader.
*/
require __DIR__ . '/vendor/autoload.php';
/*
* Create dependency injection container.
*/
$container = new ContainerBuilder();
$fileLocator = new FileLocator(__DIR__ . '/config');
$loader = new YamlFileLoader($container, $fileLocator);
$loader->load('services.yml');
$container->compile();
/*
* Create ServerRequest instance.
*/
$serverRequest = $container->get(\MyTests\ServerRequest::class);
{
"require": {
"php": ">=5.5.0",
"symfony/dependency-injection": "^4.0",
"symfony/config": "^4.0",
"symfony/yaml": "^4.0"
},
"require-dev": {
"symfony/console": "^4.0",
"symfony/event-dispatcher": "^4.0",
"symfony/process": "^4.0",
"symfony/lock": "^4.0",
"symfony/debug": "^4.0",
"symfony/var-dumper": "^4.0"
},
"autoload": {
"psr-4": {
"MyTests\\": "mytests/"
}
}
}
Upvotes: 3
Views: 1352
Reputation: 4468
You can't use the php super globals in symfony as it makes your code non testable.
You should pass the environment vars to the parameters.yml and use it where it is necessary.
https://symfony.com/doc/current/configuration/external_parameters.html
https://symfony.com/doc/current/configuration.html
If you need some of the data from the user request you should get the request stack service or use a symfony expression like in the following answer:
How do I get the user IP address in Symfony2 controller?
Upvotes: 2