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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Symfony 4:如何将$ _SERVER数组作为构造函数参数传递相关的知识,希望对你有一定的参考价值。

我正在使用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'(length = 8)

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


config/services.yml:

parameters:

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

    MyTestsServerRequest:
        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 SymfonyComponentConfigFileLocator;
use SymfonyComponentDependencyInjectionContainerBuilder;
use SymfonyComponentDependencyInjectionLoaderYamlFileLoader;

/*
 * 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(MyTestsServerRequest::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/"
        }
    }
}
答案

您不能在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?

以上是关于Symfony 4:如何将$ _SERVER数组作为构造函数参数传递的主要内容,如果未能解决你的问题,请参考以下文章

将参数传递给 symfony 5.4 表单测试不起作用

Symfony 3.4 如何退出 switch_user?

如何将Symfony 3捆绑应用程序升级到Symfony 4无捆绑应用程序?

如何让 Assetic + sass 在 Windows 中与 Symfony2 一起工作?

如何在 Symfony2 配置中添加具有值的数组?

在 Symfony 4.4 流程组件中将参数作为数组传递