PHP Globals的安全替代方法(良好的编码习惯) [英] Safe alternatives to PHP Globals (Good Coding Practices)
问题描述
多年来,我在应用程序中使用global $var,$var2,...,$varn
作为方法.我已将它们用于两个主要实现:
For years I have used global $var,$var2,...,$varn
for methods in my application. I've used them for two main implementations:
获取已设置的类(例如,数据库连接),并将信息传递给显示在页面上的函数.
Getting an already set class (such as DB connection), and passing info to functions that display to page.
示例:
$output['header']['log_out'] = "Log Out";
function showPage(){
global $db, $output;
$db = ( isset( $db ) ) ? $db : new Database();
$output['header']['title'] = $db->getConfig( 'siteTitle' );
require( 'myHTMLPage.html' );
exit();
}
但是,这样做会带来性能和安全性方面的后果.
There are, however, performance and security ramifications of doing it like this.
我可以使用哪种替代方法来维护我的功能,但可以改善设计,性能和/或安全性?
What alternative practice can I use that will maintain my functionality but improve design, performance, and/or security?
这是我所问过的第一个问题,因此,如果您需要澄清,请发表评论!
推荐答案
替代方案称为依赖注入.简而言之,这意味着您将函数/类/对象需要的数据作为参数传递.
The alternative is called dependency injection. In a nutshell it means that you pass the data a function/class/object requires as parameters.
function showPage(Database $db, array &$output) {
...
}
$output['header']['log_out'] = "Log Out";
$db = new Database;
showPage($db, $output);
这有很多原因,更好:
- 本地化/封装/命名空间功能(功能主体不再具有对外部世界的隐式依赖关系,反之亦然,只要函数调用不变,您现在就可以重写任一部分而无需重写另一部分)
- 允许进行单元测试,因为您可以单独测试功能,而无需设置特定的外部环境
- 仅通过查看签名,很明显函数将对您的代码做什么
这篇关于PHP Globals的安全替代方法(良好的编码习惯)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!