Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 routing, optional prefix from database

Basically what i want to achieve is this:

I have this paths:

http://SITENAME/dashboard

http://SITENAME/users

And they are mapped to the right controllers and actions:

/**
 * @Route("/dashboard")
 */
public function dashboardAction()
{
    // handle the request
}

/**
 * @Route("/users")
 */
public function usersAction()
{
    // handle the request
}

Now I want to make these other paths to map to the same controllers and actions:

http://SITENAME/{companyName}/dashboard

http://SITENAME/{companyName}/users

companyName is a name that I check on db if exists and if not throw a NotFound Exception.

These paths will just add some filter to the queries made, basically showing the same data structure.

I know I can create other actions and put those after the previous ones in order to be catched but I'm asking if there's something clever... something like this:

/**
 * @Route("/({companyName}/)dashboard")
 */
public function dashboardAction($companyName = null)
{
    // handle the request
}

where companyName is optional.

Thanks...

UPDATE

As Manolo suggested I already tried something like this and it works:

/**
 * @Route("/dashboard")
 * @Route("/{companyName}/dashboard")
 */
public function dashboardAction($companyName = null)
{
    // handle the request
}

But I think there's a clever way of handling it...

like image 1000
dop3 Avatar asked May 26 '26 10:05

dop3


1 Answers

Look at this example: http://symfony.com/doc/current/book/routing.html#routing-with-placeholders

// src/AppBundle/Controller/BlogController.php

// ...

/**
 * @Route("/blog/{page}", defaults={"page" = 1})
 */
public function indexAction($page)
{
    // ...
}

When page is not defined in the route, it is equal to 1.

But this won't work in your case, because you defined two routes for the same action:

/dasboard

/{companyName}/dashboard

So you have two options:

1. Define two routes for the same action (weird).

2. Change your defined route to: /dashboard/{companyName} (better)

Then, you can get /dashboard and /dashboard/{companyName} with the same action.

like image 168
Manolo Avatar answered May 30 '26 03:05

Manolo