2016-09-06 54 views
2

我有一個需要允許多個URL結構的網站。例如:CakePHP不同級別的URL路由

www.examplesite.com/people/add // <-- example company 
www.otherexample.com/xyz/people/add // <-- "xyz" company (not location based) 
www.otherexample.com/florida/abc/people/add //<-- "abc" company (location based) 

每個URL都應該能夠檢測到基於URL的公司。

到目前爲止,我已經能夠解析出網址,以確定它是哪家公司,但是如何將這些額外的/florida/abc/零件添加到路線以允許其餘應用程序正常工作?

我已經嘗試了很多東西,包括在路徑文件的頂部設置一個變量到'/ florida/abc'(或者其他任何東西),然後在每個路徑前添加,但是不處理每一個控制器/動作,看起來非常受打擊或錯過/越野車。

我還使用admin前綴,因此,例如,它也需要這樣的工作:

www.otherexample.com/admin/florida/abc/people/add 

我的假設是,我需要使用routes.php文件,但我不能確定內我該如何做到這一點。

回答

0

我在web應用程序farm.ba(未由所有者維護)中使用該方法。

我做了什麼:

  • 創建表 「節點」 包含字段ID,蛞蝓,模型,foreign_key,類型,...
  • 創建自定義路線(1),(2)類來處理節點模擬
  • 後保存,存儲和緩存塞在節點模型
  • 刪除後後後,刪除緩存和節點記錄

這非常像WordPress的路由,允許你輸入自定義的蛞蝓等

編輯:

創建應用程序/庫/路由/路由器/ MultiRoute.php自定義路由類,如:

<?php 
App::uses('CakeRoute', 'Routing/Route'); 
/** 
* MultiRoute 
*/ 
class MultiRoute extends CakeRoute 
{ 

    public function parse($url) 
    { 
     // debug($url); '/florida/abc/people/add' 

     // Add custom params 
     $params = array(
      'location' => null, 
      'company' => null, 
      'controller' => 'peoples', 
     ); 

     $params += parent::parse($url); 
     // debug($params); 
     /** 
     * array(
     * 'location' => null, 
     * 'company' => null, 
     * 'controller' => 'peoples', 
     * 'named' => array(), 
     * 'pass' => array(
     *  (int) 0 => 'florida', // location 
     *  (int) 1 => 'abc', //company 
     *  (int) 2 => 'people', // controller 
     *  (int) 3 => 'add' // action, default index 
     * ), 
     * 'action' => 'index', 
     * 'plugin' => null 
     *) 
     * 
     */ 

     // reverse passed params 
     $pass = array_reverse($params['pass']); 
     // debug($pass); 
     /** 
     * array(
     *  (int) 0 => 'add', 
     *  (int) 1 => 'people', 
     *  (int) 2 => 'abc', 
     *  (int) 3 => 'florida' 
     * ) 
     */ 

     if(isset($pass[3])) { $params['location'] = $pass[3]; } 
     if(isset($pass[2])) { $params['company'] = $pass[2]; } 
     // if you need load model and find by slug, etc... 
     return $params; 
    } 

    public function match($url) 
    { 
     // implement your code 
     $params = parent::match($url); 
     return $params; 
    } 
} 
在routes.php文件

App::uses('MultiRoute', 'Lib/Routing/Route'); 

Router::connect('/admin/*', 
    array('admin' => true),// we set controller name in MultiRoute class 
    array('routeClass' => 'MultiRoute') 
    ); 

Router::connect('/*', 
    array(),// we set controller name in MultiRoute class 
    array('routeClass' => 'MultiRoute') 
    ); 

在你的控制器查找結果

使用額外的要求params,如:

$this->request->location; 
$this->request->company; 

我希望這是有幫助的。

+0

你還記得自定義路線做了什麼嗎?我將Custom Routes看作是一種選擇,但我不確定如何解決這個問題。 – Dave

+0

嗨@Dave,不幸的是,我沒有上述應用程序的代碼。我會在我編輯的答案中給你一個想法, – Salines