Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect from a Service in Symfony2

Tags:

symfony

I have a service that looks up data for a page, but if that data isn't found, should redirect to the homepage. For the life of me, I can't figure out how to do this in Sf2. There are so many different ways to work with services and router, but none seem to work.

namespace Acme\SomeBundle\Services;

use Acme\SomeBundle\Entity\Node;
use \Doctrine\ORM\EntityManager;
use \Symfony\Component\HttpKernel\Event\GetResponseEvent;
use \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use \Symfony\Bundle\FrameworkBundle\Routing\Router;
use \Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\HttpFoundation\RedirectResponse;

class NodeFinder
{

    private $em;
    private $router;

    public function __construct(EntityManager $em, Router $router)
    {

        $this->em = $em;
        $this->router = $router;

    }

    public function getNode($slug)
    {

        $node = $this->em->getRepository('SomeBundle:Node')->findOneBy(array('slug' => $slug));

        if (!$node) { //if no node found

                return  $this->router->redirect('homepage', array(), true);
        }
}
like image 927
Acyra Avatar asked May 16 '12 09:05

Acyra


2 Answers

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');
}
like image 57
sllly Avatar answered Oct 23 '22 19:10

sllly


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

like image 25
Toskan Avatar answered Oct 23 '22 19:10

Toskan