PHP全局常量是一种好的现代开发实践吗? [英] Are PHP global constants a good modern development practice?

查看:46
本文介绍了PHP全局常量是一种好的现代开发实践吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个具有大量PHP代码库的新项目。该应用程序使用了很多PHP常量( define('FOO','bar')),尤其是对于数据库连接参数。这些常量全部在单个配置文件中定义,该文件基本上由应用程序中的每个类直接 require_once()进行。

I'm working on a new project with a sizeable PHP codebase. The application uses quite a few PHP constants ( define('FOO', 'bar') ), particularly for things like database connection parameters. These constants are all defined in a single configuration file that is require_once()'d directly by basically every class in the application.

几年前,这本来是很合理的,但是从那以后,我遇到了单元测试错误,而类之间的紧密联系确实让我感到困扰。这些常量闻起来像全局变量,它们在整个应用程序代码中直接引用。

A few years ago this would have made perfect sense, but since then I've gotten the Unit Testing bug and this tight coupling between classes is really bothering me. These constants smell like global variables, and they're referenced directly throughout the application code.

这还是个好主意吗?将这些值复制到一个对象中并使用该对象(即Bean-我在上面说过)将它们通过依赖注入传递给与数据库交互的类是否合理?通过这样做,我是否可以克服PHP常数的任何好处(例如速度或其他方面)?

Is this still a good idea? Would it be reasonable to copy these values into an object and use this object (i.e. a Bean - there, I said it) to convey them via dependency injection to the the classes that interact with the database? Am I defeating any of the benefits of PHP constants (say speed or something) by doing this?

我正在考虑的另一种方法是创建单独的配置PHP测试脚本。我仍然需要找到一种方法来使要测试的类使用沙箱配置脚本而不是全局配置脚本。仍然感觉很脆弱,但是可能需要对整个应用程序进行较少的直接修改。

Another approach I'm considering would be be to create a separate configuration PHP script for testing. I'll still need to figure a way to get the classes under test to use the sandbox configuration script instead of the global configuration script. This still feels brittle, but it might require less outright modification to the entire application.

推荐答案

在我看来,应该使用常量仅在两种情况下:

In my opinion, constants should be used only in two circumstances:


  • 实际常量值(即永远不变的东西, SECONDS_PER_HOUR )。

  • 取决于OS的值,只要在任何可能的情况下应用程序都可以透明使用常量即可。

即使那样,我也会重新考虑类常量是否更合适,以免污染常量空间。

Even then, I'd reconsider whether class constants would be more appropriate so as not to pollute the constants space.

在在您遇到的情况下,我想说常量不是一个好的解决方案,因为您将希望根据使用它们的位置提供替代值。

In your situation, I'd say constants are not a good solution because you will want to provide alternative values depending on where they're used.

这篇关于PHP全局常量是一种好的现代开发实践吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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