2011-04-27 97 views
1

一個子域我有一個子「m.mydomain.com」運行的移動網頁。這一切工作正常,但我想在使用子域時刪除URL中的控制器。路由CakePHP中使用HTML的助手

m.mydomain.com/mobiles/tips 

應使用HTML的助手成爲

m.mydomain.com/tips 

目前的鏈接看起來像這樣:

$html->link('MyLink', array('controller' => 'mobiles', 'action'=> 'tips')); 

我試圖在引導路線,也有一些黑客幾種可能的解決方案,但它並沒有爲我工作了。

在CakeBakery我發現this但這並沒有解決我的問題。

沒有人有這個問題的想法?

+0

每當你去看看我的回答,請評論,如果它不工作,所以我們可以朝着一個明確的答案工作。這個問題可能會幫助很多其他人。 – Oerd 2011-04-28 16:30:23

回答

1

你所提到的頁面收集代碼:

約束:你不能有一個在此設置稱爲tipsfoo控制器

/config/routes.php

$subdomain = substr(env("HTTP_HOST"), 0, strpos(env("HTTP_HOST"), ".")); 

if(strlen($subdomain)>0 && $subdomain != "m") { 
    Router::connect('/tips',array('controller'=>'mobiles','action'=>'tips')); 
    Router::connect('/foo', array('controller'=>'mobiles','action'=>'foo')); 
    Configure::write('Site.type', 'mobile'); 
} 

/* The following is available via default routes '/{:controller}/{:action}'*/ 
// Router::connect('/mobiles/tips', 
//     array('controller' => 'mobiles', 'action'=>'tips')); 
// Router::connect('/mobiles/foo', 
//     array('controller' => 'mobiles', 'action'=>'foo')); 

在你的控制器動作:

$site_is_mobile = Configure::read('Site.type') ?: ''; 

然後在您的視圖:

<?php 

if ($site_is_mobile) { 
    // $html will take care of the 'm.example.com' part 
    $html->link('Cool Tips', '/tips'); 
    $html->link('Hot Foo', '/foo'); 
} else { 
    // $html will just output 'www.example.com' in this case 
    $html->link('Cool Tips', '/mobiles/tips'); 
    $html->link('Hot Foo', '/mobiles/foo'); 
} 

?> 

這將允許你輸出你的觀點正確的鏈接(在一個位我會告訴你如何編寫更少的代碼),但$html助手不會能夠 - 沒有任何魔力 - 使用控制器操作路由到另一個域。要知道,m.example.comwww.example.com是不同域至於$html幫手關注。現在

,如果你願意,你可以做你的控制下采取一些邏輯關你的觀點:

<?php 

$site_is_mobile = Configure::read('Site.type') ?: ''; 

if ($site_is_mobile !== '') { 
    $tips_url = '/tips'; 
    $foo_url = '/foo'; 
} else { 
    $tips_url = '/mobile/tips'; 
    $foo_url = '/mobile/foo'; 
} 

// make "urls" available to the View 
$this->set($tips_url); 
$this->set($foo_url); 

?> 

而且在你看來,你不必擔心檢查網站是否正在經由m.example.com/tipswww.example.com/mobile/tips訪問:

<?php echo $html->link("Get some kewl tips", $tips_url); ?> 

CakePHP中-1.3對於更高級的路由指Mark Story's article on custom Route classes

讓我們知道;)

+0

感謝您的幫助Oerd!這很有效,但我一直在尋找可以兩種方式工作的東西:www.mydomain.com/mobiles/tips和m.mydomain.com/tips。這可能與HTML幫手? – chris 2011-04-29 21:37:41

+0

@chris如果你有一個手機控制器,它會開箱即用,只要'your_controller'在現實中被調用'mobiles_controller.php' – Oerd 2011-04-29 23:25:03

+0

@chris,我正在更新答案 – Oerd 2011-04-29 23:45:24