問(wèn)題描述
如何在zf2中獲取與頁(yè)面請(qǐng)求相關(guān)的各種參數(shù)?像 post/get 參數(shù)、被訪問(wèn)的路由、發(fā)送的標(biāo)題和上傳的文件.
How can I get various parameters related to the page request in zf2? Like post/get parameters, the route being accessed, headers sent and files uploaded.
推薦答案
最簡(jiǎn)單的方法是使用 Params 插件,在 beta5 中引入.它具有實(shí)用方法,可以輕松訪問(wèn)不同類型的參數(shù).與往常一樣,閱讀測(cè)試可以證明對(duì)于了解應(yīng)該如何使用某物很有價(jià)值.
The easiest way to do that would be to use the Params plugin, introduced in beta5. It has utility methods to make it easy to access different types of parameters. As always, reading the tests can prove valuable to understand how something is supposed to be used.
要獲取控制器中命名參數(shù)的值,您需要為要查找的參數(shù)類型選擇適當(dāng)?shù)姆椒ú魅朊Q.
To get the value of a named parameter in a controller, you will need to select the appropriate method for the type of parameter you are looking for and pass in the name.
$this->params()->fromPost('paramname'); // From POST
$this->params()->fromQuery('paramname'); // From GET
$this->params()->fromRoute('paramname'); // From RouteMatch
$this->params()->fromHeader('paramname'); // From header
$this->params()->fromFiles('paramname'); // From file being uploaded
所有這些方法還支持默認(rèn)值,如果沒有找到給定名稱的參數(shù),將返回這些默認(rèn)值.
All of these methods also support default values that will be returned if no parameter with the given name is found.
$orderBy = $this->params()->fromQuery('orderby', 'name');
訪問(wèn) http://example.com/?orderby=birthdate 時(shí),$orderBy 的值為 birthdate.
訪問(wèn) http://example.com/ 時(shí),$orderBy 將具有 默認(rèn) 值 name.
When visiting http://example.com/?orderby=birthdate,
$orderBy will have the value birthdate.
When visiting http://example.com/,
$orderBy will have the default value name.
?
要獲取一種類型的所有參數(shù),只需不要傳入任何內(nèi)容,Params 插件將返回一個(gè)以名稱為鍵的值數(shù)組.
To get all parameters of one type, just don't pass in anything and the Params plugin will return an array of values with their names as keys.
$allGetValues = $this->params()->fromQuery(); // empty method call
訪問(wèn)http://example.com/?orderby=birthdate&filter=hasphone時(shí) $allGetValues 將是一個(gè)類似
array(
'orderby' => 'birthdate',
'filter' => 'hasphone',
);
如果您查看源代碼 對(duì)于 Params 插件,您將看到它只是其他控制器的薄包裝器,以允許更一致的參數(shù)檢索.如果您出于某種原因想要/需要直接訪問(wèn)它們,您可以在源代碼中看到它是如何完成的.
If you check the source code for the Params plugin, you will see that it's just a thin wrapper around other controllers to allow for more consistent parameter retrieval. If you for some reason want/need to access them directly, you can see in the source code how it's done.
$this->getRequest()->getRequest('name', 'default');
$this->getEvent()->getRouteMatch()->getParam('name', 'default');
注意:您可以使用超全局變量 $_GET、$_POST 等,但不鼓勵(lì)這樣做.
NOTE: You could have used the superglobals $_GET, $_POST etc., but that is discouraged.
這篇關(guān)于如何在 Zend Framework 2 中訪問(wèn)路由、發(fā)布、獲取等參數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!