jeudi 12 mars 2015

Avoiding inheritance, how could I give my class a default creation dependency?

Say I have a class:



use App/Jedi;
use App/Interfaces/Teacher; // <-- Jedi is an implementation of Teacher

class AnakinSkywalker implements Apprenticeable;
{
private $teacher;
public $lightSaberColor = "blue";

public function __construct(Jedi $teacher){ // <-- default Teacher
$this->setTeacher($teacher);
}

public function setTeacher(Teacher $teacher){ // <-- can change later here
$this->teacher = $teacher;
}

public function printHowManyCanTeach(){
echo $teacher->count();
}

// ...
}


Lots of places in my app I use it like this:



$character = new AnakinSkywalker;
echo $character->howManyCanTeach(); // prints "Many masters"
...


But one day I decide somewhere specific in my app I need to do this instead:



$sith = new Sith; // <-- Sith is an implementation of Teacher
$characher = (new AnakinSkywalker)->setTeacher($sith);
echo $character->howManyCanTeach(); // prints "Always two there are, no more, no less"
...


Is this a proper, loosely coupled solution to give an object a default dependency with the ability to change it out later? If not, why, and what could I do to accomplish this?


Aucun commentaire:

Enregistrer un commentaire