I donβt know how you defined your service, but the example below works fine. Assuming you are calling a service on your controller.
services.yml
services: application_backend.service.user: class: Application\BackendBundle\Service\UserService arguments: - @router
Class of service
namespace Application\BackendBundle\Service; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Routing\RouterInterface; class UserService { private $router; public function __construct( RouterInterface $router ) { $this->router = $router; } public function create() { $user = new User(); $user->setUsername('hello'); $this->entityManager->persist($user); $this->entityManager->flush(); return new RedirectResponse($this->router->generate('application_frontend_default_index')); } }
controller
public function createAction(Request $request) {
UPDATE
Although the original answer above answers the original question, this is not the best practice, so do the following if you want better. First of all, do not put @router into operation and make the following changes.
// Service public function create() { ..... $user = new User(); $user->setUsername('hello'); $this->entityManager->persist($user); $this->entityManager->flush(); ..... } // Controller public function createAction(Request $request) { try { $this->userService->create(); return new RedirectResponse($this->router->generate(........); } catch (......) { throw new BadRequestHttpException(.....); } }
Bentcoder
source share