절차적인 프로그래머는 이것을보고 바보라고 생각할 것입니다. 그러나 이것으로 살아갈 수 있습니다. 이것은 output_buffer가 제거 된 후에 HTML 템플릿이있는 OOP 응용 프로그램을 사용한다고 가정합니다.
항상 한 번의 호출로 대다수의 코드를 포괄하는 try/catch 블록을 작성합니다. 일반적으로 개발 중에 output_buffer를 시작하는 것 외에도 다른 파일을 요구하기 시작합니다.
ob_start();
try {
switch($appPage) {
case('work'):
require_once('im_bored_at_work.php');
break;
case('home'):
require_once('im_a_little_less_bored_at_home.php');
break;
default:
require_once('on_the_fence.php');
}
} catch (Exception $e) {
// Handle exception caught and apply formatting
}
$devOut = ob_get_contents();
ob_end_flush();
난 당신이 사용자 정의 클래스를 잡기 위해 필요한 여러 예외를 처리 할 방법을 예제를 제공합니다
class CustomExceptionHandler extends Exception {
private $msg;
private $code;
private $otherVars;
public function __construct($msg,$code=0,$otherDebugVar=null){
$this->msg = $msg != null ? $msg : "An unknown exception was thrown";
$this->code = $code;
$this->otherVars = $otherDebugVar;
parent::__construct($msg,$code);
}
public function getOtherVars() {
return $this->otherVars;
}
}
생각은 때를 예외 객체 내에서 사용자 정보를 유지하는 것입니다 try/catch 블록의 끝에서 예외를 다시 던진다. 형식화 된 사용자 정의 메시지를 포함하는 표준 예외로, 필요한 모든 정보가 다운 스트림이되어서 어떤 예외 처리기가 원래 예외를 선택했는지는 중요하지 않다. 원래의 try/catch 블록에 걸렸습니다.
어쨌든 거친 생각입니다
try {
$html = new BasicTemplate($temp,$path);
} catch {CustomExceptionHandler $e) {
throw new Exception("Message: {$e->getMessage()} Other Info: {$e->getOtherVars()}",$e->getCode());
}
, 그것은 도움이되기를 바랍니다 :
class BasicTemplate {
private $template;
private $path;
private $contents;
public function __construct($template, $path) {
$this->template = $template;
$this->path = $path;
$this->buildTemplate();
}
private function buildTemplate() {
if ($contents = @file_get_contents($this->path . $this->template)) {
$this->contents = $contents;
} else {
$e = new CustomExceptionHandler("Message",2,$this->path . $this->template);
// Do whatever else you want to do with custom exception handling class
throw $e;
}
}
}
지금 당신은 당신의 예외를 잡아 그것을 다시 발생합니다.
여기에서 당신의 논리를 생각해 보려는 중이며, 예외 처리를위한 여분의 코드가 많이 있습니다. 필자는 예외를 잡을 때 결선 이외의 각 클래스에 대한 맞춤 예외 처리기를 만드는 경향이 있습니다. 고객 오류 메시지, 오류 코드 및 내 맞춤 처리기에서 생성 한 백 트레이스를 표준 예외로 재현합니다. 이 방법으로 모든 예외를 선택하고 확장 된 예외 처리기에서 메서드를 호출하여 필요한 경우 코드로 드릴 다운합니다. –
@DavidBarker, 이러한 예외 중 하나는 PDO를 통해 발생하는 PDOException입니다. 모든 코드 또는 모든 PDO 함수를 try-catch 블록으로 래핑 할 수 없기 때문에 그냥 잡아서 처리하는 것이 더 쉽다고 생각합니다. 그렇지 않니? – Shoe
PHP에 대해 많이 알지는 못했지만 오버로드 된 "렌더링"방법이 더 편리해 보입니다. 예외를 잡을 때 유형을 알고 있습니다. PHP가 오버로딩을 지원하지 않는다면 renderEx1, renderEx2 등을 만들 수 있습니다. – dsboger