2011-11-09 8 views
0

「Place」、「Person」、「Action」の3つのオブジェクトがあるとします。オブジェクトコンポジションからデータを取得

人がいる場所とこの人の年齢によって、この人は異なる行動を取ることができます。例えば

:私はアクションクラスからオブジェクト「人」と「場所」についてのデータにアクセスするにはどうすればよい

$place->person->action->drive(); // OK if place is "parking" and "person" is 18+ 
$place->person->action->learn(); // OK if the place is "school" and person is less than 18. 

クラス例:

class Place { 
    public $person; 
    private $name; 

    function __construct($place, $person) { 
     $this->name = $place; 
     $this->person = $person; 
    } 

} 

class Person { 
    public $action; 
    private $name; 
    private $age; 

    function __construct($name, $age) { 
     $this->name = $name; 
     $this->age = $age; 
     $this->action = new Action(); 
    } 
} 

class Action { 
    public function drive() { 
     // How can I access the person's Age ? 
     // How can I acess the place Name ? 
    } 

    public function learn() { 
     // ... Same problem. 
    } 
} 

私はアクションオブジェクト(すなわちます$ this->アクションは=新しいアクション($ this)を。)を作成したときに、私は人からのアクションに "$これを" 伝えることができると思いますプレイスのデータはどうですか?

答えて

0

PersonをPlaceやActionのプロパティをPersonのプロパティにすることは意味がありません。

私は人と場所のプロパティの公共ゲッターを作成する傾向も、それらのアクションの注射用の特性にするか、少なくともアクションのメソッドに引数として渡すのいずれか、例えば

class Place 
{ 
    private $name; 

    public function __construct($name) 
    { 
     $this->name = $name; 
    } 

    public function getName() 
    { 
     return $this->name; 
    } 
} 

class Person 
{ 
    private $name; 
    private $age; 

    public function __construct($name, $age) 
    { 
     $this->name = $name; 
     $this->age = $age; 
    } 

    public function getName() 
    { 
     return $this->name; 
    } 

    public function getAge() 
    { 
     return $this->age(); 
    } 
} 

class Action 
{ 
    private $person; 
    private $place; 

    public function __constuct(Person $person, Place $place) 
    { 
     $this->person = $person; 
     $this->place = $place; 
    } 

    public function drive() 
    { 
     if ($this->person->getAge() < 18) { 
      throw new Exception('Too young to drive!'); 
     } 

     if ($this->place->getName() != 'parking') { 
      throw new Exception("Not parking, can't drive!"); 
     } 

     // start driving 
    } 
} 
たい
関連する問題