Symfony:使用全局变量 [英] Symfony: Using global variables

查看:59
本文介绍了Symfony:使用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道...远离全局变量.

I know... stay away from globals.

实际上,我确实需要具有一个可访问的值,并且最重要的是可以从应用程序的不同部分进行可修改.这是我出于调试目的需要监视的某些操作的计数器.搜寻与Symfony和全局变量有关的任何内容,总是让我得到建议使用Container参数或Twig全局变量的结果,但根据Symfony文档,事实是这样:

The thing is I really, really, need to have a value that is accessible and, most important modifiable from different parts of the application. It's a counter for some actions that I need to watch for debug purposes. Googling for anything related to Symfony and globals, always got me to results that suggests using the Container parameters or Twig globals, but the thing is that according to Symfony documentation:

您只能在编译容器之前设置参数:不能在运行时设置.

You can only set a parameter before the container is compiled: not at run-time.

鉴于我需要控制器中的而不是视野中的Twig全局变量,因此超出了范围.

The Twig globals are pretty much out of scope given that I need them in controller, not in view.

恕我直言,这两种解决方案都更像是常量而不是变量.

IMHO, both of these solutions are more like constants than variables.

因此,问题是:是否有最佳实践来使用Symfony获得我需要的东西,还是应该只使用PHP全局变量?

So, the question is: Is there a best practice to obtain what I need using Symfony or should I just use the PHP globals?

谢谢!

推荐答案

使用私有属性 $ counter 以及公共setter和getter创建服务(例如: ApplicationGlobals )读取和写入值.服务类将自动实例化,并且可以在您可以使用容器的任何地方(将其放入控制器或将其作为参数传递给其他服务)访问.

Create a service (e.g: ApplicationGlobals) with a private property $counter and public setter and getter to read and write the value. A service class will be instantiated automatically and can be reached from everywhere where you can use the container (get it in the controller or pass it as an argument to other services).

稍后,您将能够在需要时添加带有适当的getter和setter的多个变量,并在项目中使用它们.

Latter you will be able to add multiple variables, when needed, with their proper getters and setters and use them in your project.

我认为您甚至可以编写一个在Symfony终止时存储新值的析构函数. http://symfony.com/doc/current/service_container.html#creating-configuring-services-in-container

I think you could even write a destructor that stores the new value when Symfony terminates. http://symfony.com/doc/current/service_container.html#creating-configuring-services-in-the-container

这篇关于Symfony:使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆