I am using laravel as framework and I love the Eloquent objects. But now I have an Eloquent object, which only is allowed to be created within specific functions. In normal cases I would make the constructor and the static create method private, and call them from static functions within this class.
My class looks like this:
class Action extends Model {
public static function create(array $attributes = []) {
parent::create($attributes);
}
private static function customCreate(ActionType $action, Country $from, Country $to){
self::create([
'action' => $action,
'country_from_id' => $from->id,
'country_to_id' => $to->id,
]);
}
public static function attack(Country $from, Country $to) {
if($from->hasNeighbour($to)){
return new self(ActionType::attack(), $from, $to);
}
throw new InvalidActionException('Only neighbours can attack each other');
}
}
In a 'perfect world' I would like to have it look like the following:
class Action extends Model {
private static function create(ActionType $action, Country $from, Country $to){
parent::create([
'action' => $action,
'country_from_id' => $from->id,
'country_to_id' => $to->id,
]);
}
public static function attack(Country $from, Country $to) {
if($from->hasNeighbour($to)){
return new self(ActionType::attack(), $from, $to);
}
throw new InvalidActionException('Only neighbours can attack each other');
}
}
But this 'perfect world' solution is not allowed by php because of 2 failures. The first one is I can't override a public method by a private method. The second failure is the create method is not compatible with the eloquent create method (the eloquent method requires the arguments array $attributes = []
)...
What is the best solution to achieve something beautiful like my 'perfect world' solution?