Zend Framework: Can i just get GET params?

2019-03-25 18:13发布

In Zend Framework, most of the time to get a param, i will use

// from controller
$this->getRequest()->getParam('key');

but how can i get just GET params using the 'Zend' way? Or do i just use $_GET? Is there any difference between

$this->getRequest()->getParam('key');

vs

$_GET['key'];

4条回答
Emotional °昔
2楼-- · 2019-03-25 18:27

This works for ZF2

$this->params()->fromQuery('key', 1); // second argument is optional default paramter
查看更多
萌系小妹纸
3楼-- · 2019-03-25 18:33

Use getQuery():

$this->_request->getQuery('key');

Other methods available include

  • getParam()
  • getQuery()
  • getPost()
  • getCookie()
  • getServer()
  • getEnv()

getParam() checks user params first, then $_GET, and then $_POST, returning the first match found or null.

Try to avoid accessing the superglobals directly.

查看更多
我只想做你的唯一
4楼-- · 2019-03-25 18:42

The main difference is that

$_GET['key'];

is a dependency on the environment. It requires the superglobal to be available and containing a key of that name. It's also just a simple array access, while

$this->getRequest()->getParam('key');

is an API method call. Access to the Request is abstracted. There is no dependency on the actual environment. The Request object could be a mock. The getParam method will always return a value regardless whether it is from $_GET or $_POST.

Putting an abstraction on top of the Request is better, because it allows for more decoupling, less dependencies and therefor makes your application easier to test and maintain.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-03-25 18:42

After studying Zend 2's in depth data binding documentation, I've found that it is best to access parameters from the route via the automatically accessible Params plugin. Utilizing this plugin, you can get a parameter as shown below from within a controller.

$this->params('key');
查看更多
登录 后发表回答