在 Zend 框架中获取 "put" 方法中的 POST 参数



我使用此

获得了参数
$this->params()->fromQuery('KEY');

我找到了两种获取发布参数的方法

//first way
$this->params()->fromPost('KEY', null);
//second way
$this->getRequest()->getPost();

这两个在"邮政"方法中都起作用,但是现在以" put"方法作为后参数。

我如何在" put"方法中获取发布参数?

我想正确的方法是使用 zend_controller_plugin_puthandler

// you can put this code in your projects bootstrap
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Zend_Controller_Plugin_PutHandler());

然后您可以通过 getParams()

获得参数
foreach($this->getRequest()->getParams() as $key => $value) {
    ...
}

或简单

$this->getRequest()->getParam("myvar");

您需要阅读请求主体并解析它,类似的东西:

$putParams = array();
parse_str($this->getRequest()->getContent(), $putParams);

这将把所有参数分析到$putParams -array中,因此您可以像访问Super Globals $_POST$_GET一样访问它。例如:

// Get the parameter named 'id'
$id = $putParams['id'];
// Loop over all params
foreach($putParams as $key => $value) {
    echo 'Put-param ' . $key . ' = ' . $value . PHP_EOL;
}

我使用从AngularJS发送的数据遇到了麻烦,发现最好的方法是使用自定义Zend插件

class Web_Mvc_Plugin_JsonPutHandler extends Zend_Controller_Plugin_Abstract {
    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        if (!$request instanceof Zend_Controller_Request_Http) {
            return;
        }
        if ($this->_request->isPut()) {
            $putParams = json_decode($this->_request->getRawBody());
            $request->setParam('data', $putParams);
        }
    }
}

然后可以通过getParams作为PHP对象访问

    $data = $this->getRequest()->getParam('data');
    $id = $data->id;

最新更新