2017-10-26 12 views
2

私のアプリケーションですべてが正しいことを確認するコマンドをいくつか書きます。

これらのコマンドはcronjobによって実行されるため、出力をログファイルで悪用できるようにフォーマットしたいと思います。

コマンドのどこからでもエラーメッセージを表示するには(すべてのメソッド呼び出しで$出力を渡さずに)クラスプロパティにしておくと便利ですが、悪いと思われますが、理由を知っている。ここに例があります:

<?php 
namespace CheckingBundle\Command; 

use Symfony\Component\Console\Command\Command; 
use Symfony\Component\Console\Input\InputInterface; 
use Symfony\Component\Console\Output\OutputInterface; 

/** 
* Class CheckingCommand 
* 
*/ 
class CheckingCommand extends Command 
{ 
    /** 
    * @var OutputInterface $output 
    */ 
    private $output; 

    protected function configure() 
    { 
     $this->setName('check:all'); 
    } 

    protected function initialize(InputInterface $input, OutputInterface $output) 
    { 
     $this->output = $output; 
    } 

    protected function execute(InputInterface $input, OutputInterface $output) 
    { 
     $this->checkSqlConnection(); 
    } 

    protected function checkSqlConnection() 
    { 
     $myConnexion = null; //Try to connect to database 
     if (null === $myConnexion) { 
      $this->sendError('Cannot connect to MySQL database'); 
     } 
    } 

    /** 
    * @param string $errorMessage 
    */ 
    protected function sendError($errorMessage) 
    { 
     $this->output->write(sprintf('%s <error>%s</error>', date('Y-m-d H:i:s'), $errorMessage)); 
    } 
} 

誰かが私になぜそれが悪いのか説明できますか?私はのtry/catchで私のコマンド内部例外を使用してキャッチで私のsendErrorメソッドを使用する必要があり

$this->checkSqlConnection($output); 

protected function checkSqlConnection(Output $output) 
    { 
     $myConnexion = null; //Try to connect to database 
     if (null === $myConnexion) { 
      $output->write('Cannot connect to MySQL database'); 
     } 
    } 

:次のようにどこにでもそれを渡す方が良いのではないでしょうか?これはエラーを処理する良い方法ですが、他の情報をメソッド内に表示したいのですが?

+3

これはかなり主観的ですが、出力をフォーマットする 'command'クラスの責任ではないので、私は '悪い'と思います。あなたは 'OutputFormatter'を持っていなければなりません。 – bassxzero

答えて

1

1)checkSqlConnectionは、コマンドクラスには含めないでください。別のクラス(サービスかもしれません)にする必要があります。このクラスをサービスとして公開する必要があります。あなたはそれが周り$input$outputインスタンスを渡すために良いコードではありません述べたように、コマンドクラスから、それは、あなたのビジネス・ロジックは、サービスクラスが緊密に結合されるので、それはよくないですが、コマンドクラス

2)にすべきではありません入出力クラス

ソリューション? symfonyの2.4コンソールコンポーネントは、モノローグと統合され、それがコンソールイベントをリッスンし、ログレベルとコンソールの冗長性に応じて、コンソール出力にログメッセージを書き込み、コンソールハンドラを持っているのと代わりoutputInterfaceのモノローグ、 を使用

Read more

関連する問題