ilSavo
ilSavo

Reputation: 846

Add dynamic route in Symfony1.4

I'd like to know, if possible, if I can add/register a new route dynamically, based on some paremeter.

I know that a route is somethig like

newsdetail:
    url: /newsdetail/:id/:title
    class: sfDoctrineRoute
    options: { model: News, type object }
    param: { module: articles, action: articledetail }
    requirements: 
        id: \d+
        sf_method: [get]

But now, is there a way for me to add, or prepend this kind of route in an action? My problem is that the module and the action could change depending of the site instance...

So, I've built a component that do something and two different modules, suppose module1 and module2, both two including the component. For different reasons, I can't register in the routing file all these routes. Now, the user1 have to have the route that go to module1, and the user2 have to have the route for the module2. So, I'd like to add the route in an action. I hope I have explained it better

Upvotes: 0

Views: 1109

Answers (2)

Pipe
Pipe

Reputation: 2424

Why don't you have the same routing and change the content based on credentials?

Upvotes: 0

j0k
j0k

Reputation: 22756

Here is an example about building dynamic route.

Basically:

  • you add a listener to the event routing.load_configuration
  • this listener retrieve routes from the database and prepend them to the current routing cache

Here is a cleaned snippet:

<?php

class frontendConfiguration extends sfApplicationConfiguration
{
  public function configure()
  {
    $this->dispatcher->connect('routing.load_configuration', array($this, 'listenToRoutingLoadConfigurationEvent'));
  }

  public function listenToRoutingLoadConfigurationEvent(sfEvent $event)
  { 
    $routing    = $event->getSubject(); 
    $products   = Doctrine::getTable('Product')->findAll();

    foreach ($products as $product)
    {
      if (0 == strlen($product->route))
      {
        continue;
      }

      $name  = 'product_'.$product->id;
      $route = new sfRoute(
        $product->route,
        array('module' => 'browse', 'action' => 'catalog', 'product' => $product->id),
        array('product' => '\d+'),
        array('extra_parameters_as_query_string' => false)
      );

      $routing->prependRoute($name, $route);
    }
  }
}

Edit:

You can retrieve routing from an action using the context:

$this->getContext()->getRouting()

So, if you want to add a route from the action, you can do the following:

$route = new sfRoute(
  '/my-route',
  array('module' => 'browse', 'action' => 'catalog', 'product' => 456),
  array('product' => '\d+'),
  array('extra_parameters_as_query_string' => false)
);

$this->getContext()->getRouting()->prependRoute('my-route', $route);

Anyway, I still don't really understand how you want to make it... Even after your last edit.

Upvotes: 1

Related Questions