A typical Developer Blog
by Gordon Franke
Icon

Wie kann ich dynamische Urls mit Symfony erstellen?

Ich habe eine einfache article Tabelle mit einer id und einer title Spalte.
Ich möchte urls wie diese generieren.

/my-title-4
/:title-:id

Außerdem soll automatisch zur aktuellen url umgeleitet werden wenn sich der title ändert.

Lösung

hinzufügen einer neuen route routing.yml:

article_detail:
  url:     /:slug
  class:   sfDoctrineRoute
  options: { model: Article, type: object, method: getBySlug }
  param:   { module: offer, action: show }
  requirements:
    slug: .+-\d+
    sf_method: [get]

getBySlug Funktion definieren in lib/model/doctrine/ArticleTable.class.php:

1
2
3
4
5
6
7
8
9
10
public function getBySlug(array $parameters)
{
  if(!preg_match('/\d+$/', $parameters['slug'], $matches))
  {
    return null;
  }
  list($id) = $matches;
 
  return $this->find($id);
}

folgenden Code zur show action hinzufügen:

1
2
3
4
5
6
7
8
9
10
public function executeShow(sfWebRequest $request)
{
  $this->article = $this->getRoute()->getObject();
  $this->forward404Unless($this->article);
 
  if($request->getParameter('slug') != $this->article->getslug())
  {
    $this->redirect($this->generateUrl('article_detail', $this->article));
  }
}

No related posts.

Ähnliche Artikel bereitgestellt von Yet Another Related Posts Plugin.

Author:

Category: symfony, Uncategorized

Tagged: , , ,

Leave a Reply

CommentLuv badge