Here's something that I've been thinking about for some time. I want to chain together a set of methods like in the below shown example.
The concept of method chaining is no brainer, but what I want is to make all of our animals be added through the same add
method, so how should I figure out what type of animal that we're adding inside the add
method?
$zoo = new Zoo;
$lion = $zoo->lion->add('Lucas the lion');
$cockatoo = $zoo->cockatoo->add('Chris the cockatoo');
class Zoo {
function add($name) {
//How to figure out if the animal is a Lion or an Cockatoo?
}
}
One solution to the problem would be to override __get in the Zoo class to return a 'creator' class.
function __get($animal){
return new Creator($this, $animal);
}
Then let the creator class call the add function in the zoo class.
class Creator{
public function __construct($zoo, $animal){
....
}
public function add($details){
$zoo->add($this->_animal, $details);
}
}
This solution is fairly ugly, and from a future developers perspective, not that clear. As pointed out in the comments, there are better ways about going this. Doing something like:
$zoo->add('lion', 'whatever')
or
$zoo->add( new Lion('Whatever') )
May be a better solution and in my opinion it is far clear to other developers what is happening. (This may not be the case for you, as I don't know the details of exactly what you are doing).
Since we're talking about Object Oriented Design it would be much more "correct" and flexible to implement hierarchy like:
interface IAnimal {}
class Lion implements IAnimal {}
class Zoo
{
private $animals = array();
public function add(IAnimal $animal)
{
$this->animals[] = $animal;
return $animal;
}
}
$zoo = new Zoo();
$lion = $zoo->add(new Lion('Lucas'));