代码之家  ›  专栏  ›  技术社区  ›  Rikijs

symfony在帮助程序服务中重定向不起作用

  •  0
  • Rikijs  · 技术社区  · 6 年前

    介绍

    对于我的个人项目,我使用

    • Symfony v4.2 具有
    • XAMPP
    • Widows 10 Pro

    为了不在URL中显示路由参数,我将它们保存在表中。 然后,在控制器中,我检查会话中是否存在变量(保持与路由参数对应的UUID)。

    如果在会话中没有得到变量,那么它应该重定向到节的起始页,其中UUID和表中的初始数据是设置好的。

    重定向逻辑被提取到助手服务。为了重定向到工作,有复制的函数 redirectToRoute redirect

    我通过删除temp文件夹中的php会话变量和浏览器中的phpsessid cookie来测试这个功能。

    问题

    Prolem是-它不会重定向到扇区起始页。

    如果选择了分支,我可以看到它是正确的,但是它“只是停止”并且不执行重定向。

    代码

    public function checkWhereaboutsExist()
    {
       $em = $this->entityManager;
       $repo_whereabouts = $em->getRepository(Whereabouts::class);
    
       $whereabouts = $this->session->get('whereabouts');
       if (($whereabouts === null) || ($whereabouts === ''))
       {
           $data = 'whereabouts === '.$whereabouts;
           dump($data);
           /*
           HERE IT STOPS
           */
           return $this->redirectToRoute('section_start');
       }
       else
       {
           $my_whereabouts = $repo_whereabouts->getWhereabouts($whereabouts);
           if (!$my_whereabouts)
           {
               return $this->redirectToRoute('section_start');
           }
       }
    }
    

    问题

    Enyone对本案的罪魁祸首有什么看法吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Robert Saylor    6 年前

    您可以尝试将路由器注入到服务类中:

    use Symfony\Component\Routing\RouterInterface;
    

    MyService类 { 专用$router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }
    
    public function checkWhereaboutsExist()
    {
        // your code ...
    
        return new RedirectResponse($this->router->generate('section_start'));
    }
    

    }

        2
  •  1
  •   ArGh    6 年前

    嗯,我想您的代码在服务中,而不是在控制器中? 您不能从服务重定向,只能从控制器作为控制器发送最终响应。

    您必须从服务返回一个布尔值并从控制器重定向:

    public function hasToGoToStart()
    {
       $em = $this->entityManager;
       $repo_whereabouts = $em->getRepository(Whereabouts::class);
    
       $whereabouts = $this->session->get('whereabouts');
       if (($whereabouts === null) || ($whereabouts === ''))
       {
           return true;
       }
       else
       {
           $my_whereabouts = $repo_whereabouts->getWhereabouts($whereabouts);
           if (!$my_whereabouts)
           {
               return true;
           }
       }
    
       return false;
    }
    

    在控制器中:

    if ($myService->hasToGoToStart()) {
        // redirect
    }