从Symfony2中的服务重定向

时间:2012-05-16 09:22:23

标签: symfony

我有一个查找页面数据的服务,但是如果找不到该数据,则应该重定向到主页。对于我的生活,我无法弄清楚如何在Sf2中做到这一点。有很多不同的方法可以使用服务和路由器,但似乎都没有。

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);
        }
}

4 个答案:

答案 0 :(得分:6)

在Symfony2中,不会为重定向提供服务。您应该尝试更改您的服务:

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;
    }
}

然后在你的控制器中你调用你的服务并进行重定向:

// in the controller file

$nodefinder = $this->container->get('your_node_finder_service_name');

if (!$nodefinder->getNode($slug)) {
    $this->redirect('homepage');
}

答案 1 :(得分:5)

你可以在你的服务中做到这一点(写下我的脑袋)

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;
        }
    }
}

虽然这并不完美,但肯定比试图做的好多了

答案 2 :(得分:2)

在您的服务中注入路由器服务。您可以返回新的RedirectResponse 。看here

答案 3 :(得分:1)

从Symfony的角度来看,您可以将控制器创建为服务,从而从此服务进行重定向。 语法是:

use Symfony\Component\HttpFoundation\RedirectResponse;

return new RedirectResponse($url, $status);

可以在此处找到更多信息:http://symfony.com/doc/current/cookbook/controller/service.html#alternatives-to-base-controller-methods