私のアプリケーションですべてが正しいことを確認するコマンドをいくつか書きます。
これらのコマンドは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');
}
}
:次のようにどこにでもそれを渡す方が良いのではないでしょうか?これはエラーを処理する良い方法ですが、他の情報をメソッド内に表示したいのですが?
これはかなり主観的ですが、出力をフォーマットする 'command'クラスの責任ではないので、私は '悪い'と思います。あなたは 'OutputFormatter'を持っていなければなりません。 – bassxzero