2011-10-26 16 views
5

當我在Zend中所說的路由器象下面這樣:在Zend中操作後獲取所有參數?

coupon/index/search/cat/1/page/1/x/111/y/222

而且控制器內部,當我得到$this->_params,我得到一個數組:

array(
    'module' => 'coupon', 
    'controller' => 'index', 
    'action' => 'search', 
    'cat' => '1', 
    'page' => '1', 
    'x' => '111', 
    'y' => '222' 
) 

但我只想得到:

array(
    'cat' => '1', 
    'page' => '1', 
    'x' => '111', 
    'y' => '222' 
) 

請問你能告訴我一種方法,在t之後得到所有的paramsaction

回答

6

據我所知,您將始終在params列表中獲取控制器,操作和模塊,因爲它是默認的一部分。你可以做這樣的事情,除去三從你的陣列:

$url_params = $this->getRequest()->getUserParams(); 
    if(isset($url_params['controller'])) 
     unset($url_params['controller']); 
    if(isset($url_params['action'])) 
     unset($url_params['action']); 
    if (isset($url_params['module'])) 
     unset($url_params['module']); 

或者你不想做,每次你需要的資源列表的時間,創建一個幫手爲你做,是這樣的:

class Helper_Myparams extends Zend_Controller_Action_Helper_Abstract 
{ 
    public $params; 

    public function __construct() 
    { 
     $request = Zend_Controller_Front::getInstance()->getRequest(); 
     $this->params = $request->getParams(); 
    } 

    public function myparams() 
    {  
     if(isset($this->params['controller'])) 
      unset($this->params['controller']); 
     if(isset($this->params['action'])) 
      unset($this->params['action']); 
     if (isset($this->params['module'])) 
      unset($this->params['module']); 
     return $this->params; 
    } 

    public function direct() 
    { 
     return $this->myparams(); 
    } 
} 

而且你可以簡單地從您的控制器調用這個以獲取列表:

$this->_helper->myparams(); 

因此,例如使用url:

http://127.0.0.1/testing/urls/cat/1/page/1/x/111/y/222 

和代碼:

echo "<pre>"; 
print_r($this->_helper->myparams()); 
echo "</pre>"; 

我得到以下陣列印刷:

Array 
(
    [cat] => 1 
    [page] => 1 
    [x] => 111 
    [y] => 222 
) 
+0

如果'$ this-> getRequest() - > getParams()'返回期望值,爲什麼需要編寫一個幫助器? –

+0

因爲如果你閱讀海報問題,它不會返回期望值,海報__不想要數組中的控制器,動作和模塊。 '$ this-> getRequest() - > getParams()'__WILL__將它們返回到它的數組中。因此,使用'unset'去除它們 - 但是如果數組將要被使用幾次或者在不同的控制器中使用,那麼在控制器中使用幫助器和更少的代碼會更容易。 – Scoobler

3

這個怎麼樣?

在控制器:

$params = $this->getRequest()->getParams(); 
unset($params['module']; 
unset($params['controller']; 
unset($params['action']; 

漂亮笨重;可能需要一些isset()檢查以避免警告;可能會將此部分堵塞到自己的方法或助手中。但它會完成這項工作,對吧?

+0

查看@ Scoobler的回答,很好地填寫了我提到的細節。 –

10

IMHO這是更優雅和包括在動作變化,控制器和方法鍵。

$request = $this->getRequest(); 
$diffArray = array(
    $request->getActionKey(), 
    $request->getControllerKey(), 
    $request->getModuleKey() 
); 
$params = array_diff_key(
    $request->getUserParams(), 
    array_flip($diffArray) 
); 
+0

我怎麼說「非常感謝你」。愛你的答案。 – vietean

+0

確實,這是優雅的。 ;-) –

相關問題