Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Symfony2中的服务重定向_Symfony - Fatal编程技术网

从Symfony2中的服务重定向

从Symfony2中的服务重定向,symfony,Symfony,我有一个服务可以查找页面的数据,但是如果找不到数据,应该重定向到主页。就我个人而言,我不知道如何在Sf2中做到这一点。使用服务和路由器有很多不同的方法,但似乎没有一种有效 namespace Acme\SomeBundle\Services; use Acme\SomeBundle\Entity\Node; use \Doctrine\ORM\EntityManager; use \Symfony\Component\HttpKernel\Event\GetResponseEvent; use

我有一个服务可以查找页面的数据,但是如果找不到数据,应该重定向到主页。就我个人而言,我不知道如何在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);
        }
}

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

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


虽然这并不完美,但它肯定比SLLY试图做的要好得多

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

use Symfony\Component\HttpFoundation\RedirectResponse;

return new RedirectResponse($url, $status);

更多信息可在此处找到:

在您的服务中插入路由器服务。然后您可以返回一个新的重定向响应。瞧。

谢谢你。问题是我在很多地方都使用这项服务,因此在控制器中执行重定向时有大量代码重复。斯利是对的,你应该在控制器中执行任何重定向,而不是在服务中执行任何重定向。@ChrisMcKinnel因为?我有很多次
如果用户没有登录,重定向到登录页面
真的吗?我要把这个复制100次?糟透了
use Symfony\Component\HttpFoundation\RedirectResponse;

return new RedirectResponse($url, $status);