7

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

4 回答 4

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');
}
于 2012-05-16T09:43:00.223 回答
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;
        }
    }
}

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

于 2014-06-09T22:33:55.340 回答
2

在你的服务中注入路由器服务。比你可以返回一个新的 RedirectResponse。看这里

于 2016-02-22T10:31:27.720 回答
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

于 2016-01-18T18:41:03.613 回答