我目前正在尝试通过在终端中执行命令来执行 CRON 作业。但它会引发以下错误。
PHP Fatal error: Call to a member function has() on a non-object in /MyProject/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php on line 161
这是我在命令文件中的代码。
namespace MyProject\UtilityBundle\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class projectOngoingCommand extends Command
{
protected function configure()
{
$this
->setName('projectOngoingEstimation:submit')
->setDescription('Submit Ongoing Project Estimation')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
;
$projectController= new \MyProject\ProjectBundle\Controller\DefaultController();
$msg = $projectController->updateMonthlyOngoingAllocation();
$output->writeln($msg);
}
}
这是我在默认 Controller 中的代码。
// cron job code
public function updateMonthlyOngoingAllocation() {
$em = $this->getDoctrine()->getEntityManager();
$project = $this->getDoctrine()->getRepository('MyProjectEntityBundle:Project')
->getAllOngoingProjectList();
return "hello";
}
使用命令成功调用该方法
sudo php 应用程序/控制台项目OngoingEstimation:提交
但它在第一行抛出错误。即
$em = $this->getDoctrine()->getEntityManager();
当我尝试从 Controller 内的另一个 Action 方法调用该函数时,它工作正常。
最佳答案
我认为您在这里使用的策略不正确。您尝试在命令中调用 Controller ,根据错误消息,这似乎不是一个好主意。
您应该创建一个服务并在您的 Controller 和命令中调用该服务。
class ProjectManager
{
private $em;
public function __construct(EntityManager $em) {
$this->em = $em;
}
public function updateMonthlyOngoingAllocation() {
$project = $this->em->getRepository('MyProjectEntityBundle:Project')
->getAllOngoingProjectList();
return "hello";
}
}
然后在config.yml中
services:
project_manager:
class: MyBundle\Manager\ProjectManager
arguments: ["@doctrine.orm.entity_manager"]
现在您可以调用此服务:
- 从您的 Controller 使用
$this->get('project_manager')->updateMonthlyOngoingAllocation()
- 使用
$this->getContainer()->get('project_manager') 从您的命令(如果您的类从
ContainerAwareCommand
而不是Command
扩展) ->updateMonthlyOngoingAllocation()
关于symfony - 在 Symfony2 中通过命令行执行时,CRON 作业不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10546379/