【问题标题】:unable to access controller functions in command line or console application无法在命令行或控制台应用程序中访问控制器功能
【发布时间】:2017-08-21 02:50:57
【问题描述】:

我正在准备一个控制台应用程序并使用实体管理器的容器连接到数据库。这工作正常。代码如下

protected function execute(InputInterface $input, OutputInterface $output)
{
    // get Doctrine
    $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
    // find all disc that are not treated by Manager in last week i.e sysdate - 6
    $pendingApprovals = $this->em->getRepository('GMRestBundle:TDtlsDisc')->getPendingManagerAppoval();
    // for each unapproved disc, start sending emails

    $repository = $this->em->getRepository('GMRestBundle:TDtlsDisc');
    $emailReminder = new SubmitDisclosureController();      
    foreach($pendingApprovals as $labManagerReview) {           
        $tDtlsDiscEntity = $repository->findByDiscId($labManagerReview['DISC_ID']);
        $emailReminder->sendMailToLabManager($tDtlsDiscEntity);
    }
}

现在,问题是当我调用 thsi $emailReminder->sendMailToLabManager($tDtlsDiscEntity); 时出现错误,这将反过来建立 orm 连接并从数据库中获取一些数据。这个sendMailToLabManager 在SubmitDisclosureController 中,代码如下。

public function sendMailToLabManager($tDtlsDiscEntity)
{
    $repository = $this->getDoctrine()->getRepository('GMRestBundle:TXrefDiscSso');
    $entityRepository = $this->getDoctrine()->getRepository('GMRestBundle:TDtlsEntity');
    $discId = $tDtlsDiscEntity->getDiscId();
.......

在控制台应用程序中,我无法使用任何控制器通过与学说对象建立另一个连接来访问数据库。如果我通过 web 中的另一个动作控制器调用相同的控制器,它运行良好。

 Error: Call to a member function has() on null

我现在看到上面的错误消息。

【问题讨论】:

  • $emailReminder->setContainer($this->getContainer()) 会让你跳过错误消息,但你不应该直接调用控制器方法。使您的 EmailReminder 成为一个独立的服务,然后与命令和控制器共享它:symfony.com/doc/current/service_container.html 理解服务是有效使用 Symfony 框架的关键部分。

标签: doctrine-orm console-application symfony-2.6


【解决方案1】:

您应该创建一个提供该功能的服务,而不是使用控制器。之后,您必须通过依赖注入将EntityManager 插入到服务中。

如果您的命令为extends ContainerAwareCommand,您可以在命令中使用$this->get() 来检索您之前定义的服务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    相关资源
    最近更新 更多