2012-04-26 29 views
0

我讀過有關的永久鏈接(隱藏主鍵並用顯著字符串替換它們)段,但我不明白它是如何工作的代碼:的symfony:固定鏈接(URL中隱藏ID)

public function executePermalink($request) 
    { 
    $article = ArticlePeer::retrieveBySlug($request->getParameter('slug'); 
    $this->forward404Unless($article); // Display 404 if no article matches slug 
    $this->article = $article;   // Pass the object to the template 
    } 

這個代碼是推動的典型代表,是不是?教義上有這樣的東西嗎?我必須編寫retrieveBySlug()函數?你有一個例子,我可以理解如何寫它?

非常感謝

回答

1

教義您有一個名爲「Sluggable」的擴展,你可以使用。

爲了使它工作,你必須改變你的schema.yml並添加 「Sluggable」 擴展名:

# config/doctrine/schema.yml 
Article: 
    actAs: 
    Timestampable: ~ 
    Sluggable: 
     fields: [name] 
    columns: 
    name: 
     type: string(255) 
     notnull: true 

建立一個DoctrineRoute在你的routing.yml

# apps/frontend/config/routing.yml 
category: 
    url:  /article/:slug 
    class: sfDoctrineRoute 
    param: { module: article, action: show } 
    options: { model: Article, type: object } 

然後在你的你可以這樣做的代碼:

public function executeShow(sfWebRequest $request) 
{ 
    $this->article = $this->getRoute()->getObject(); 
    $this->forward404Unless($article); // Display 404 if no article matches slug 
    $this->article = $article;   // Pass the object to the template 
} 

不要忘了運行一個教條:build to re在改變模式後創建數據庫。

+0

完善,得益於有一個錯誤。我會試試看。 – satboy78 2012-04-26 20:01:28

+0

@ilanco由於'$ this-> getRoute() - > getObject()'已經執行了檢查,所以你可以使用'forward404Unless'去除支票。 – j0k 2012-04-26 20:08:47

+0

嗨,我試了一下......它給了我一些問題,但我已經解決了它(在答案中,我解釋了我是如何做到的......) – satboy78 2012-05-03 08:27:24

0

現在工作正常!

# apps/frontend/config/routing.yml 
opera_slug: 
    url: /:sf_culture/opere/:operaslug.html 
    class: sfDoctrineRoute 
    param: { module: opera, action: permalink } 
    options: { model: Opera, type: object } 
    requirements: 
    sf_culture: (?:it|en|es|fr) 



    public function executePermalink(sfWebRequest $request) 
    { 
    $this->opera = $this->getRoute()->getObject(); 
    $this->forward404Unless($this->opera); // Display 404 if no article matches slug 
    //$this->opera = $opera;   // Pass the object to the template 
    } 

正如你所看到的,我已經修改了最後executePermalink()的兩行,因爲我用你的函數

+0

不錯,但你可以用.html代替。 sf_format並添加到requiremet sf_format:html – 2013-11-28 14:36:48