2012-05-11 48 views
2

我目前正嘗試通過在終端中執行命令來執行CRON作業。但它會引發以下錯誤。當通過Symfony2中的命令行執行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 

這是我在Command文件中的代碼。

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

這是我在默認控制器中的代碼。

// cron job code 
    public function updateMonthlyOngoingAllocation() { 

       $em = $this->getDoctrine()->getEntityManager(); 
     $project = $this->getDoctrine()->getRepository('MyProjectEntityBundle:Project') 
        ->getAllOngoingProjectList(); 
     return "hello"; 
     } 

這種方法被成功調用使用命令

sudo php app/console projectOngoingEstimation:submit

但它引發錯誤的第一行。即

$em = $this->getDoctrine()->getEntityManager(); 

當我試圖從控制器內的另一個Action方法調用該函數的工作正常。

回答

2

我不認爲你在這裏使用正確的策略。你嘗試在你的命令中調用你的控制器,並根據你的錯誤信息,它似乎不是一個好主意。

你應該創建一個服務並在你的Controller和你的Command中調用這個服務。

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"] 

現在你可以調用這個服務:

  • 從控制器$this->get('project_manager')->updateMonthlyOngoingAllocation()
  • 從您的命令(如果你的類擴展從ContainerAwareCommand而不是Command)與$this->getContainer()->get('project_manager')->updateMonthlyOngoingAllocation()
0

您只要做以下幾點。無需注入任何東西,因爲控制檯可以識別容器。

public function updateMonthlyOngoingAllocation() { 
        $project = $this->getContainer() 
          ->get('doctrine') 
          ->getRepository('MyProjectEntityBundle:Project') 
          ->getAllOngoingProjectList(); 
      return "hello"; 
      }