使用方式html
/** * 若是直接示例化 Request 默認是沒有參數的,能夠本身傳入 * 本方法將 PHP 超全局變量做爲參數而後實例化自身(Request)進行初始化。 */ $request = Request::createFromGlobals();
表面的 Request 對象格式cookie
+ 是公開屬性,# 是受保護屬性,- 是私有屬性post
源碼中 Request 參數的初始化過程this
/** * 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 參數包裝細節spa
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; } // 其它實現的方法 // ... }
小結code
經過以上了解,徹底透過 OOP 方式能夠訪問請求過程當中的任何參數。orm
$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 提供了不少封裝的便捷方法。server
$request->getScriptName(); # 等同 $request->server->get('SCRIPT_NAME');