【问题标题】:New alternative for getDoctrine() in Symfony 5.4 and upSymfony 5.4 及更高版本中 getDoctrine() 的新替代方案
【发布时间】:2022-01-09 16:00:27
【问题描述】:

正如我的 IDE 所指出的,AbstractController::getDoctrine() 方法现在已被弃用。

我在官方文档和 Github 变更日志中都没有找到任何关于此弃用的参考。

此快捷方式的新替代方案或解决方法是什么?

【问题讨论】:

    标签: php symfony symfony5


    【解决方案1】:

    如上所述here

    不要使用那些快捷方式,而是在构造函数或控制器方法中注入相关服务。

    你需要使用依赖注入。

    对于给定的控制器,只需在控制器的构造函数中注入ManagerRegistry

    
    use Doctrine\Persistence\ManagerRegistry;
    
    class SomeController {
    
        public function __construct(private ManagerRegistry $doctrine) {}
    
        public function someAction(Request $request) {
            // access Doctrine
            $this->doctrine;
        }
    } 
    

    【讨论】:

      【解决方案2】:

      您可以使用 EntityManagerInterface $entityManager:

      public function delete(Request $request, Test $test, EntityManagerInterface $entityManager): Response
      {
          if ($this->isCsrfTokenValid('delete'.$test->getId(), $request->request->get('_token'))) {
              $entityManager->remove($test);
              $entityManager->flush();
          }
      
          return $this->redirectToRoute('test_index', [], Response::HTTP_SEE_OTHER);
      }
      

      【讨论】:

        猜你喜欢
        • 2015-09-11
        • 2014-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-15
        • 2023-02-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多