2015-06-12 55 views
0

我有一個網絡應用程序,可以讓用戶進行多次搜索,並在同一頁面上顯示搜索結果。使用zend框架傳遞網址上的數組2路線

這是一個基本結構:

Search 1 
- Attribute 1 = X 
- Attribute 3 = Y 

Search 2 
-Attribute 2 = Z 

所有這些結果被加載到使用Ajax請求我的網頁。這裏的問題是,如果用戶想要將搜索結果顯示給某人,他將無法做到這一點,因爲url保持不變。

要解決這個問題,我可能會使用JavaScript按壓狀態或替換狀態:https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

我的問題是與Zend 2閱讀這些網址並解析它。我想有一些是用戶友好的這樣的:

www.example.com/Search/Attribute1-X-Attribute3-Y/Search/Attribute2-Z 

這樣做是爲了獲得這樣的事情我控制器上:

$this->getParam('Search');//Array('Attribute1-x-Attribute3-Y','Attribute2-Z'); 

我知道我們可以用這種方式完成類似的東西:

?a[]=1&a[]=2&a[]=3 

但是,這不是我正在尋找的機器人。

如何使用zf2路線完成此任何幫助?

回答

0

由於我沒有反饋,我不得不採取一種解決方法。以下是我成功地完成我問:

首先,而是採用:

www.example.com/Search/Attribute1-X-Attribute3-Y/Search/Attribute2-Z 

我以前是這樣的:

www.example.com/Search/Attribute1/X/Attribute3/Y/Search/Attribute2/Z 

我第一次使用正則表達式來這條路對我module.config:

'search' => array(
      'type' => 'Application\Router\SearchesImprovedRegex', 
      'options' => array(
       'regex' => '(/Search((/Attribute1/(?<attr1>[a-zA-Z-]+)){0,1}(/Attribute2/(?<attr2>[a-zA-Z-]+)){0,1}(/Attribute3/(?<attr3>[a-zA-Z-]+)){0,1}))+', 
       'defaults' => array(
        'controller' => 'Application\Controller\Index', 
        'action' => 'index', 
       ), 
       'spec'=> '/' 
      ), 
     ), 

然後我創建了自己的類,擴展的Zend \的mvc \路由器\ HTTP \正則表達式和IM贊成RouterInterface。我只需要重寫匹配函數來使它對屬性有一些不同的解析。

<?php 
namespace Application\Router; 
use Zend\Mvc\Router\Http\Regex as Regex; 
use Zend\Mvc\Router\Http\RouteMatch; 
use Zend\Stdlib\RequestInterface as Request; 
/** 
* Regex route. 
*/ 
class SearchesImprovedRegex extends Regex { 

/** 
* match(): defined by RouteInterface interface. 
* 
* @param Request $request 
* @param int $pathOffset 
* @return RouteMatch|null 
*/ 
public function match(Request $request, $pathOffset = null) { 
    if (!method_exists($request, 'getUri')) { 
     return null; 
    } 

    $uri = $request->getUri(); 
    $path = $uri->getPath(); 

    $auxPath = explode('/Search', $path); 
    $searches = Array(); 


    for ($i = 1; $i < count($auxPath); $i++) { 
     $search = array(); 
     $path = '/Search' . $auxPath[$i]; 

     if ($pathOffset !== null) { 
      $result = preg_match('(\G' . $this->regex . ')', $path, $matches, null, $pathOffset); 
     } else { 
      $result = preg_match('(^' . $this->regex . '$)', $path, $matches); 
     } 

     if (!$result) { 
      return null; 
     } 

     $matchedLength = strlen($matches[0]); 

     foreach ($matches as $key => $value) { 
      if (is_numeric($key) || is_int($key) || $value === '') { 
       unset($matches[$key]); 
      } else { 
       $search[$key] = rawurldecode($value); 
      } 
     } 
     array_push($searches, $search); 
    } 
    $matches = Array('Searches' => $searches); 

    return new RouteMatch(array_merge($this->defaults, $matches), $matchedLength); 
} 
} 

然後在控制器:

var_dump($this->params('Searches'));