1

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?

Jetse
  • 1,706
  • 2
  • 16
  • 22
  • did you try avoiding static ..to make it same as the title http://stackoverflow.com/questions/2223386/why-doesnt-java-allow-overriding-of-static-methods – zod Oct 08 '15 at 21:41
  • In PHP it is allowed to override static methods, and I want to override the static method because the parent static method allows creation of wrong Action instances... – Jetse Oct 09 '15 at 08:44

0 Answers0