3
votes

currently, I'm trying to implement a few routes to symfony 2.5 that lead me to a little problem. I need to have an url scheme that has the same route depending on a custom service.

route_category:
    pattern: /{location}/{category}
    defaults: { _controller: LocationBundle:Category:index }
    condition: "service('location_category_service').isCategory(request.get('category')) == true"

route_merchant:
    pattern: /{location}/{merchant}
    defaults: { _controller: LocationBundle:Merchant:index }
    condition: "service('location_merchant_service').isMerchant(request.get('merchant')) == true"

What I want symfony to do is:

Given URL path: /germany/restaurants

  • try matching route 1
  • "isCategory" returns true, so this route matches

Given URL path: /germany/aldi

  • try matching route 1
  • "isCategory" returns false, so we skip this route
  • try matching route 2
  • "isMerchant" returns true, so this route matches and we execute the MerchantController

Given URL path: /germany/this-does-not-match-anything

  • try matching route 1
  • "isCategory" returns false, so we skip this route
  • try matching route 2
  • "isMerchant" returns false, so we skip this route
  • ... now we can execute the default behaviour when no route matches

I thought, that the condition would exactly does what I want, but I only have the requestContext and the request in the expression language, not the service container.

Does anybody know, how I can inject the service container to the expression language for routing purposes or maybe something else that would help to solve this problem?

Thanks in advance :-)

1
sorry for OT, but how did you get service(...) to work? I'm trying to use service in condition, but all I get is The function "service" does not exist around position 1.ex3v

1 Answers

1
votes

Having two variables like this is troublesome. From experience the best practice is to separate these two with a static value like so:

route_category:
    pattern: /{location}/category/{category}

route_merchant:
    pattern: /{location}/merchant/{merchant}

Otherwise as David Kmenta said you will be writing extra code trying to figure out what is what.

Ask yourself if that type of coding is worth having one less extra word in your urls?

To add to this, think of your users: if you have a merchant that sounds like a category will they know the difference or will the scheme you're after just confuse them.