Symfony 4:如何将$ _SERVER数组作为构造函数参数传递

时间:2017-12-10 19:16:02

标签: php symfony dependency-injection constructor yaml

我正在使用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)

也许你有个主意?非常感谢你!

配置/ services.yml:

parameters:

services:
    _defaults:
        autowire: false
        autoconfigure: true
        public: true

    MyTests\ServerRequest:
        arguments:
            $serverParams: $_SERVER

mytests / ServerRequest.php

<?php

namespace MyTests;

class ServerRequest {

    private $serverParams;

    public function __construct($serverParams) {
        $this->serverParams = $serverParams;

        echo 'Hello from ServerRequest!<br/>';

        var_dump($this->serverParams);
    }

}

bootstrap.php中

<?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);

composer.json

{
    "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/"
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您无法在symfony中使用php超级全局变量,因为它会使您的代码无法测试。

您应该将环境变量传递给parameters.yml并在必要时使用它。

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

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

如果您需要来自用户请求的一些数据,您应该获得请求堆栈服务或使用symfony表达式,如下面的答案:

How do I get the user IP address in Symfony2 controller?