简体   繁体   中英

Symfony 2 - Using custom service in routing expression

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 :-)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM