[SF] Symfony 标准 HttpFoundation\Request 实现分析

使用方式

/**
* 如果直接示例化 Request 默认是没有参数的,可以自己传入
* 本方法将 PHP 超全局变量作为参数然后实例化自身(Request)进行初始化。
*/
$request = Request::createFromGlobals();

表面的 Request 对象格式

[SF] Symfony 标准 HttpFoundation\Request 实现分析

+ 是公开属性,# 是受保护属性,- 是私有属性

源码中 Request 参数的初始化过程

    /**
* Sets the parameters for this request.
*
* This method also re-initializes all properties.
*
* @param array $query The GET parameters
* @param array $request The POST parameters
* @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
* @param array $cookies The COOKIE parameters
* @param array $files The FILES parameters
* @param array $server The SERVER parameters
* @param string|resource $content The raw body data
*/
public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
$this->request = new ParameterBag($request);
$this->query = new ParameterBag($query);
$this->attributes = new ParameterBag($attributes);
$this->cookies = new ParameterBag($cookies);
$this->files = new FileBag($files);
$this->server = new ServerBag($server);
$this->headers = new HeaderBag($this->server->getHeaders()); $this->content = $content;
$this->languages = null;
$this->charsets = null;
$this->encodings = null;
$this->acceptableContentTypes = null;
$this->pathInfo = null;
$this->requestUri = null;
$this->baseUrl = null;
$this->basePath = null;
$this->method = null;
$this->format = null;
}

源码中 ParameterBag 参数包装细节

class ParameterBag implements \IteratorAggregate, \Countable
{
/**
* Parameter storage.
*/
protected $parameters; /**
* @param array $parameters An array of parameters
*/
public function __construct(array $parameters = array())
{
$this->parameters = $parameters;
} /**
* Returns the parameters.
*
* @return array An array of parameters
*/
public function all()
{
return $this->parameters;
} // 其它实现的方法
// ...

小结

通过以上了解,完全透过 OOP 方式可以访问请求过程中的任何参数。

$request->attributes->get('q');
$request->server->get('SCRIPT_NAME');
$request->query->all( );
$request->request->keys();
$request->cookies->remove('sc');
$request->get('q'); # 依次从 attributes,query,request 检测是否有key的值,有就返回;兼容 get、post 方法时使用,否则建议访问对应公开属性上的方法,例如:$request->query->get('q');

并且 Request 提供了很多封装的便捷方法。

$request->getScriptName(); # 等同 $request->server->get('SCRIPT_NAME');

Link:https://www.cnblogs.com/farwish/p/9615790.html

上一篇:LeetCode() 数字1的个数


下一篇:python time库