2012-05-11 11 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 

これはコマンドファイル内のコードです。

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

コントローラ内で別のアクションメソッドから関数を呼び出そうとしたときに問題なく動作します。

答えて

2

私はここで適切な戦略を使用するとは思わない。コマンドでコントローラを呼び出そうとしましたが、エラーメッセージによれば、それは良い考えではありません。

サービスを作成し、このサービスをコントローラとコマンド内で呼び出す必要があります。

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()
  • であなたのコマンドから(自分のクラスが拡張する場合Commandの代わりにContainerAwareCommandから)$this->getContainer()->get('project_manager')->updateMonthlyOngoingAllocation()
0

あなたは次のようにしてください。コンソールはコンテナを認識しているので、何も注入する必要はありません。

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