Redirect from a Service in Symfony2 Redirect from a Service in Symfony2 symfony symfony

Redirect from a Service in Symfony2


In Symfony2, services are not made for redirections. You should try to change your service like that :

namespace Acme\SomeBundle\Services;use Acme\SomeBundle\Entity\Node;use \Doctrine\ORM\EntityManager;class NodeFinder{    private $em;    public function __construct(EntityManager $em)    {        $this->em = $em;    }    public function getNode($slug)    {        $node = $this->em->getRepository('SomeBundle:Node')->findOneBy(array(            'slug' => $slug        ));        return ($node) ? true : false;    }}

then in you controller you call your service and make the redirection :

// in the controller file$nodefinder = $this->container->get('your_node_finder_service_name');if (!$nodefinder->getNode($slug)) {    $this->redirect('homepage');}


you could do this in your service ( writing out of my head)

class MyException extends \Exception{    /**     * @var \Symfony\Component\HttpFoundation\RedirectResponse     */    public $redirectResponse;}class MyService {        public function doStuff()     {        if ($errorSituation) {            $me = new MyException()            $me->redirectResponse = $this->redirect($this->generateUrl('loginpage'));            throw $me;         }    }}class MyController extends Controller{    public function doAction()    {        try {            // call MyService here        } catch (MyException $e) {            return $e->redirectResponse;        }    }}

Although this is not perfect, it is certainly a lot better than what sllly was trying to do


Inject the router service in your service. Than you can return a new RedirectResponse. Look here.