从 Symfony2 中的服务重定向 [英] Redirect from a Service in Symfony2

查看:28
本文介绍了从 Symfony2 中的服务重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

这篇关于从 Symfony2 中的服务重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆