0

私はこのシナリオを持っています:

Interface ClassInterface 
{
  public function getContext();
}

Class A implements ClassInterface 
{
  public function getContext()
  {
     return 'CONTEXTA';
  }

  //Called in controller class
  public function Amethod1() 
  {
    try {
       //assuming that Helper is a property of this class
        $this->helper->helperMethod($this);
     } catch(Exception $ex) {
       throw $ex;
     }
  }
}

Class B implements ClassInterface 
{
  public function getContext()
  {
     return 'CONTEXTB';
  }

  //Called in controller class
  public function Bmethod1() 
  {
     try {
       //assuming that Helper is a property of this class
        $this->helper->helperMethod($this);
     } catch(Exception $ex) {
       throw $ex;
     }
  }

}

Class Helper {
 public function helperMethod(ClassInterface $interface) 
 {
   try {
      $this->verifyContext($interface->getContext());
      //dosomething
   } catch(\Exception $ex) {
     throw $ex;
   }

 }

 private function verifyContext($context) {
    if (condition1) {
       throw new \UnexpectedValueException('Invalid context.');
    }

    return true;
 }

}

Amethod1 と Bmethod1 を呼び出すコントローラー クラスに、プロセスでスローされた例外の種類を認識させたいと考えています。提示されたのと同じように例外を再スローすることをお勧めしますか? この場合、スロー-キャッチ-スロー-キャッチ-スロー構造は合理的だと思いますか?

4

1 に答える 1

0

はい、まったく合理的です。しかし:あなたの特定の例は次から単純化できます:

public function Amethod1() 
{
   try {
      //assuming that Helper is a property of this class
      $this->helper->helperMethod($this);
   } catch(Exception $ex) {
      throw $ex;
   }
}

に:

public function Amethod1() 
{

    //assuming that Helper is a property of this class
    $this->helper->helperMethod($this);
}
于 2012-08-12T14:07:02.847 に答える