在PHP中直接使用superglobals是好还是坏? [英] Is using superglobals directly good or bad in PHP?

查看:170
本文介绍了在PHP中直接使用superglobals是好还是坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我不是来自庞大的PHP背景 - 我想知道是否在格式良好的代码中,应该直接使用'superglobals',例如在某些函数的中间,如 $ _ SESSION ['x'] ='y'; 或者如果像我通常对变量所做的那样,最好将它们作为可以从那里使用的参数,例如:

  class Doer {
private $ sess;
public function __construct(& $ sess){
$ this-> sess =& $ SESS;
}
}

$ doer = new Doer($ _ SESSION);

,然后使用 Doer-> sess Doer内部的版本等。 (这种方法的优点是它清楚地表明 Doer 使用$ _SESSION。)



接受的PHP这个问题的设计方法是什么?

解决方案

我喜欢包装 $ _ SESSION $ _POST $ _GET $ _ COOKIE 进入OOP结构。



我使用这种方法来集中处理卫生和验证的代码,所有必需的 isset() check,nonces, setcookie 参数等。它还允许客户端代码更具可读性(并且让我错觉它更易于维护)。



执行这种结构可能很困难,尤其是在有多个编码器的情况下。用 $ _GET $ _POST $ _ COOKIE (我相信),你的初始化代码可以复制数据,然后摧毁超全局。也许一个聪明的析构函数可以使$ _SESSION成为可能(在加载时擦除$ _SESSION,并将它写回析构函数),尽管我还没有尝试过。

不过,我通常不会使用这些强制技术。习惯之后,在会话类以外的代码中看到 $ _ SESSION 看起来很奇怪,而且我大部分都是单独工作。



编辑

以下是一些示例客户端代码,以防有人帮助。我相信看看任何主要的框架都会给你更好的想法......

  $ post = Post :: load (); 
$ post-> numeric('member_age');
$ post-> email('member_email');
$ post-> match('/ regex /','member_field');
$ post-> required('member_first_name','member_email');
$ post-> inSet('member_status',array('unemployed','retired','兼职','全职'));
$ post-> money('member_salary');
$ post-> register('member_last_name'); //没有具体要求,但是我们想要访问
if($ post-> isValid())
{
//做好东西
$ firstName = $ post-> ; member_first_name;
}
else
{
//做错误的东西
}



Post和它的朋友都来自一个基类,它实现了核心验证代码,添加了他们自己特定的功能,如表单标记,会话cookie配置等等。



在调用验证方法时,类内部保存了从 $ _ POST 中提取的有效数据集合,然后使用魔术 __ get 方法。失败的字段不能以这种方式访问​​。我的验证方法(除必需)不会在空字段上失败,其中许多方法使用 func_get_args 来允许它们一次在多个领域进行操作。某些方法(如 money )会自动将数据转换为自定义值类型。



在错误情况下,我有一种方法可以将数据转换为可以保存在会话中的格式,并用于预先填充表单并在重定向到原始表单后突出显示错误。



改进此方法的一种方法是将验证信息存储在Form类中,该类用于呈现表单和电源客户端验证,并在提交后清理数据。


So, I don't come from a huge PHP background—and I was wondering if in well formed code, one should use the 'superglobals' directly, e.g. in the middle of some function say $_SESSION['x'] = 'y'; or if, like I'd normally do with variables, it's better to send them as arguments that can be used from there, e.g:

class Doer {
    private $sess;
    public function __construct(&$sess) {
        $this->sess =& $sess;
    }
} 

$doer = new Doer($_SESSION);

and then use the Doer->sess version from within Doer and such. (The advantage of this method is that it makes clear that Doer uses $_SESSION.)

What's the accepted PHP design approach for this problem?

解决方案

I do like to wrap $_SESSION, $_POST, $_GET, and $_COOKIE into OOP structures.

I use this method to centralize code that handles sanitation and validation, all of the necessary isset () checks, nonces, setcookie parameters, etc. It also allows client code to be more readable (and gives me the illusion that it's more maintainable).

It may be difficult to enforce use of this kind of structure, especially if there are multiple coders. With $_GET, $_POST, and $_COOKIE (I believe), your initialization code can copy the data, then destroy the superglobal. Maybe a clever destructor could make this possible with $_SESSION (wipe $_SESSION on load, write it back in the destructor), though I haven't tried.

I don't usually use any of these enforcement techniques, though. After getting used to it, seeing $_SESSION in code outside the session class just looks strange, and I mostly work solo.

EDIT
Here's some sample client code, in case it helps somebody. I'm sure looking at any of the major frameworks would give you better ideas...

$post = Post::load ();  
$post->numeric ('member_age');  
$post->email ('member_email');
$post->match ('/regex/','member_field');
$post->required ('member_first_name','member_email');
$post->inSet ('member_status',array('unemployed','retired','part-time','full-time'));
$post->money ('member_salary');
$post->register ('member_last_name'); // no specific requirements, but we want access
if ($post->isValid())
{
  // do good stuff
  $firstName = $post->member_first_name;
}
else
{
  // do error stuff
}

Post and its friends all derive from a base class that implements the core validation code, adding their own specific functionality like form tokens, session cookie configuration, whatever.

Internally, the class holds a collection of valid data that's extracted from $_POST as the validation methods are called, then returns them as properties using a magic __get method. Failed fields can't be accessed this way. My validation methods (except required) don't fail on empty fields, and many of them use func_get_args to allow them to operate on multiple fields at once. Some of the methods (like money) automatically translate the data into custom value types.

In the error case, I have a way to transform the data into a format that can be saved in the session and used to pre-populate the form and highlight errors after redirecting to the original form.

One way to improve on this would be to store the validation info in a Form class that's used to render the form and power client-side validation, as well as cleaning the data after submission.

这篇关于在PHP中直接使用superglobals是好还是坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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