2012-05-16 9 views
7

ページのデータを検索するサービスがありますが、そのデータが見つからない場合は、ホームページにリダイレクトする必要があります。私の人生にとって、私はSf2でこれをどうやって行うのか分かりません。サービスやルーターを扱うにはさまざまな方法がありますが、どれもうまくいかないようです。Symfony2のサービスからのリダイレクト

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

答えて

6

サービスではリダイレクトが行われません。あなたはそのようなあなたのサービスを変更しようとする必要があります:

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

ありがとうございます。問題は、私はこのサービスを多くの場所で使用しているため、コントローラでリダイレクトを行うコードの重複がたくさんあることです。 – Acyra

+0

Slllyが正しいです、あなたはあなたのサービスではなく、あなたのコントローラでリダイレクトを行うべきです。 @ChrisMcKinnelの理由から –

+3

?私は何度も 'ユーザーがログインしていない場合、ログインページにリダイレクトする'ことがありますか?私はこれを100回複製する必要がありますか?悪い悪い悪い – Toskan

4

あなたはあなたのサービスでこれを行うことができます(私の頭の外に書きます)

class MyException extends \Exception{ 
public $redirectResponse; //is a \Symfony\Component\HttpFoundation\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が

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

2

は、あなたのサービスでルータサービスを注入します。 の新しいRedirectResponseを返すことができます。 Look hereをご覧ください。

関連する問題