0

So I got this in my routing.yml:

requirements:
    var1: \d+
    var2: \d+

Both are checked on their own and valid. I need to check the combination of the 2, since the combination is not always valid.

For this case I need to check the relation between 2 objects in the database, the first should be the parent of the second. I can do this in the controller, but I don't really like that implementation. Also, I need this same check for more than 1 route.

How would I add another requirement that checks the combination? Can I define a method in the controller class that would be called?

Or would the best solution be something like:

public function indexAction($var1, $var2)
{
    $result = $this->checkRelation($var1, $var2);
    if ($result) {
        // return errorpage
        return $result;
    }

    // ... 
}
DoppyNL
  • 1,415
  • 1
  • 14
  • 24
  • I think you should add more informations : what type of combination is it? What sort of validation? (should show the controller's code that correspond to it for example) – MisterJ May 10 '13 at 11:40
  • You are right. Added info on database relation. But there might be other cases were "custom checks" might be needed where the routing-config doesn't support it. – DoppyNL May 10 '13 at 11:49

2 Answers2

0

So as I understand your question, you want the following:

/parent/child/        --> returns 200
/not_parent/not_child --> returns 404

The Symfony2 Routing component doesn't do this natively, but you could extend it.

http://symfony.com/doc/master/cmf/cookbook/using-a-custom-route-repository.html

Dan Blows
  • 20,846
  • 10
  • 65
  • 96
  • I can find in the documentation how to create a custom validator, however, I cannot find how to use this in routing.yml. The documentation appears to state it to be only for validating entity's, not route's. – DoppyNL May 10 '13 at 12:24
  • Sorry, I obviously didn't read your question properly. Editing now. – Dan Blows May 10 '13 at 12:27
  • Yup, that is what I'm looking for. Suggested solution does seem a bit overkill. I might be better of in keeping the check in the controller. I do know that when the combination is invalid, there will not be another route that does match. – DoppyNL May 10 '13 at 12:37
0

The final solution I went with was the following:

  • add a method checkRelation that requires all parameters
  • run a query inside that method to check if everything is ok.
  • return false when there is a problem, return true when values are ok. (alternatively you can return an object or something)
  • in the action I check if the value is false, if so I return a generic "not found" page for the specific controller.

In all this is very similar to what I posted in my initial question.

When using the same checkRelation in multiple controllers it might be a good idea to move it (partially) to a repository-class or something similar to prevent duplication of code/logic.

DoppyNL
  • 1,415
  • 1
  • 14
  • 24