Search code examples
symfony1doctrinepermalinks

symfony: permalinks (hide id in urls)


I've read the paragraph about permalinks (hide primary keys and replace them with significant strings) but I can't understand how it works this code:

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
  }

This code is typical of propel, is it right? there is something like it for doctrine? I've to write the retrieveBySlug() function? do you have an example where I can understand how to write it?

Thanks a lot


Solution

  • In Doctrine you have an extension called "Sluggable" you can use.

    To make it work you have to change your schema.yml and add the "Sluggable" extension:

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

    Set up a DoctrineRoute in your routing.yml

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

    Then in your code for the action you can do something like this :

    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
    }
    

    Don't forget to run a doctrine:build to recreate the database after you alter your schema.