2017-10-26 1 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)); 
    } 
} 

누군가가 나에게 왜 나쁜지 설명 할 수 있습니까?

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

내가 시도/캐치 내 명령 내부 예외를 사용하고 잡아 내 대해 sendError의 방법을 사용해야합니다 : 모든 곳에서 같은 그것을 전달하는 더 나은하지 않을까요? 이것은 오류를 처리하는 좋은 방법이 될 수 있지만 다른 정보를 메서드 내에서 표시하려면 어떻게해야합니까?

+3

이것은 꽤 주관적이지만 출력을 형식화하는'command' 클래스의 책임이 아니기 때문에 '나쁘다'고 생각합니다. 당신은'OutputFormatter' 또는 그밖에 그 책임을 처리해야합니다. – bassxzero

답변

1

내가 지적하고 싶은 두 가지가있다 1) checkSqlConnection 명령 클래스에 있으면 안됩니다, 그것은 별도의 클래스 (아마 서비스)에 있어야 당신은 서비스 사용으로이 클래스를 노출 할 필요가 명령 클래스에서 귀하의 비즈니스 로직이 명령 클래스에 있어서는 안됩니다.

2) 언급 한대로 $input$output 인스턴스를 전달하는 코드가 좋지 않습니다. 서비스 클래스가 입출력 클래스

솔루션? 심포니 2.4 콘솔 구성 요소 독백과 통합하고 콘솔 이벤트를 수신하고 로그 수준과 콘솔 상세에 따라 콘솔 출력에 로그 메시지를 기록 콘솔 핸들러가의로 대신 outputInterface의 독백, 를 사용

Read more

관련 문제