A
A
Alexander Evgenievich2015-11-12 17:59:56
symfony
Alexander Evgenievich, 2015-11-12 17:59:56

How to bypass code duplication in Symfony2 controller?

Hello.
The question is next. There are links to access resources. Resources have a certain hierarchy, for example, the link will look like this:

/cart/{cartId}/product/{productId}

And accordingly, we have GET, POST, PUT, PATCH, DELETE methods. With each request to Actions, we need to check if there is a basket with this ID, if there is a product with this ID, if I have the right to work with the product, etc., and if the condition does not match, an HTTPException is thrown.
So the question has come up, in order not to duplicate the code for Action-methods of controllers, how is it better to do such a pre-check of typical conditions?
There were thoughts to put everything in a regular manager, but I don’t think that throwing HTTPExceptions by a manager is a good idea. I also thought about putting such a check in the RequestListener, but so far I have a vague idea of ​​​​how this will work. At the moment, type checks have been moved to traits, and the controller has been implemented from the interface with methods, as in a trait.
Is there any best solution for this problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2015-11-12
@banderos120

There were thoughts to put everything in a regular manager, but I don’t think that throwing HTTPExceptions by a manager is a good idea.

Yes, because FosRestBundle has such a thing as an ErrorController that can convert ordinary exceptions into a correct response with its own status codes.
Bringing all these things into your service manager, so that all the business logic is nearby, is a sound idea.

S
shagguboy, 2015-11-12
@shagguboy

https://knpuniversity.com/screencast/symfony-journ...

V
voronkovich, 2015-11-13
@voronkovich

Your checks can be put in annotations.
To check if an entity with the desired id exists, you can use the @ParamConverter
annotation. To check access rights, you can use @Security.
All exceptions will be thrown automatically.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question