从对象组合中获取数据


Get data from object composition

假设我有3个对象:"Place", "Person", "Action"。

根据人所在的地点和年龄,人可以做出不同的动作。

例如:

$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.

如何从Action类中访问对象"Person"answers"Place"的数据?

类示例:

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"从Person传输到Action。$this->action = new action ($this)),但是Place数据呢?

让Person成为Place的属性或者Action成为Person的属性是没有意义的。

我更倾向于为Person和Place的属性创建公共getter ,要么使它们成为Action的可注入属性,要么至少将它们作为参数传递给Action的方法,例如

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
    }
}