2014-06-27 10 views
1

我有一個CakePHP的網站有許多內部聯繫,即是建立一個與HtmlHelper如何在CakePHP中的HtmlHelper#鏈接(...)調用中不更改地重新定義URL生成?

/app/View/MyController/myaction.ctp

<?php 
echo $this->Html->link(
    $item['Search']['name'], 
    array(
     'controller' => 'targetcontroller', 
     'action' => 'targetaction', 
     $profileId, 
     $languageId 
    ) 
); 
?> 

它工作正常使用默認的路由:

/app/Config/routes.php

Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display')); 

生成的鏈接如下所示:/mycontroller/myaction/$profileId/$languageId

現在我想使用搜索引擎友好的網址(配置文件名稱和ISO-639-1語言代碼,而不是標識)的網站的一部分,並增加了新的途徑:

/應用/配置/routes.php

Router::connect(
    '/:iso6391/:name.html', 
    array('controller' => 'mycontroller', 'action' => 'myaction'), 
    array(
     'iso6391' => '[a-zA-Z]+', 
     'name' => '[0-9a-zA-ZäöüßÄÖÜ\-]+', 
    ) 
); 

而且它也工作正常,像/producer/en/TestName.html的進來的URI的正確解釋。

但是HtmlHelper仍然生成舊的URI,如/mycontroller/myaction/1/1

docu說:

反向路由是CakePHP的一個特點,就是用來讓你輕鬆改變你的URL結構,而不必修改所有的代碼。通過使用路由陣列來定義您的URL,您可以稍後配置路由,並且生成的URL將自動更新。

那麼,HtmlHelper得到一個路由數組作爲輸入,這意味着:我使用反向路由。

爲什麼它不起作用?如何使HtmlHelper生成新的URL(不需要更改HtmlHelper#link(...)調用)?

回答

1

的解釋第一

位你是技術上不使用反向路由。你看,輸出鏈接/mycontroller/myaction/1/1確切地不匹配/iso/name.html。就像,絕不是。所以,路由跳過了該規則,因爲它不適用。

代碼

試試這個

echo $this->Html->link(
    $item['Search']['name'], 
    array(
     'controller' => 'targetcontroller', 
     'action' => 'targetaction', 
     'iso6391' => $someStringWithIso, 
     'name' => $someName 
    ) 
); 

但對於這一點,你必須改變你的路由了一下,因爲你沒有傳遞參數(檢查the docs的例子)

Router::connect(
    '/:iso6391/:name.html', 
    array('controller' => 'mycontroller', 'action' => 'myaction'), 
    array(
     'pass' => array('iso6391', 'name'), 
     'iso6391' => '[a-zA-Z]+', 
     'name' => '[0-9a-zA-ZäöüßÄÖÜ\-]+', 
    ) 
); 

你必須介意第一個字符串匹配/:iso6391/:name.html。您是否希望將此路線與您的項目中的每個控制器和操作相匹配,或者僅將控制器和的一個視圖匹配。如果是針對所有項目,只是爲了以防萬一,使用此

/:controller/:action/:iso6391/:name.html 

如果僅僅是,比如說,控制器1和行動「視圖」,使用

/controller1/view/:iso6391/:name.html 

你需要考慮的細節是您使用的擴展名.html,是否真的在url中需要?如果是,將其添加爲一個參數在HTML#鏈接

echo $this->Html->link(
    $item['Search']['name'], 
    array(
     'controller' => 'targetcontroller', 
     'action' => 'targetaction', 
     'iso6391' => $someStringWithIso, 
     'name' => $someName 

     'ext' => 'html' 
    ) 
); 

,並添加parseExtensions到路由文件。​​。如果你不添加擴展名會更容易,但這取決於你。

最後,你還是要你的電話改變Html->link ...

+0

謝謝你的回答,但是,正如你正確地說,這種解決方案「到最後,我還是要改變我調用Html-> link「。再次感謝,但這不是真正的解決方案。 – automatix

+1

@automatix根本無法以某種方式修改你的'HtmlHelper :: link()'調用,因爲它直接傳遞適當的反向路由值,或者使用一個自定義的幫助器來轉換傳遞的選項或其他。 .. – ndm

相關問題