我正在使用Symfony 4的The DependencyInjection Component,我正在尝试定义配置设置(在config/services.yml
中)以创建简单的ServerRequest
对象。 ServerRequest
接收$_SERVER
变量(数组)作为构造函数参数$serverParams
的参数。
它应该打印数组,但是,它打印字符串“$ _SERVER”:
来自ServerRequest的Hello!
... path-to-project-root /mytests/ServerRequest.php:14:string' $ _SERVER' (长度= 8)
也许你有个主意?非常感谢你!
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/"
}
}
}
答案 0 :(得分:2)
您无法在symfony中使用php超级全局变量,因为它会使您的代码无法测试。
您应该将环境变量传递给parameters.yml并在必要时使用它。
https://symfony.com/doc/current/configuration/external_parameters.html
https://symfony.com/doc/current/configuration.html
如果您需要来自用户请求的一些数据,您应该获得请求堆栈服务或使用symfony表达式,如下面的答案: