A developer should know which methods need to be implemented in the class. Assuming that he does not, how could we force him to implement them without checking the existance of certain methods in your other methods programatically?
That's where interfaces come in handy and what they are for. See an interface as a contract that defines which methods a class must implement.
So the cleanest way to tackle your task would be to just implement an interface.
FruitsModelInterface.php
<?php
interface FruitsModelInterface{
public function setFruitId($fruitId);
}
FruitsModel.php
<?php
class FruitsModel implements FruitsModelInterface{
protected $fruitId;
public function setFruitId($fruitId){
$this->fruitId = $fruitId;
}
public function displayFruit()
{
if(is_null($this->fruitId))
throw new FruitsModelException('Fruit ID missing!');
echo $this->fruitId;
// You'd probably better go with calling the Method
// getFruit() though and return $this->fruitId instead of echoing
// it. It's not the job ob the FruitsModel to output something
}
}
Really, that's all the magic. Just force the FruitsModelInterface to implement the setFruitId()
method by implementing the proper interface. In your displayFruit()
you just check if the property really has been assigned.
I also made your property protected, so that you can be sure the value will just be set from within the class or it's children.
Happy Coding!
Further reading