OGHaza
OGHaza

Reputation: 4795

How do I handle model inheritance in Laravel?

I have a project in which a number of models are defined using Eloquent. This is straightforward for the most part but I'm having trouble understanding how to handle a new case. I'm going to avoid using laravel/eloquent terminology in case I just obscure the problem.

I have a table called Question with fields id, QuestionTypeID, QuestionStatement.

Based on the QuestionTypeID a different class of question would need to be instantiated that may pull information for additional tables or use different business logic in the PHP code.

All of these question types could implement a common interface like:

interface Question {
    int id;
    string statement;
    function ask($params);
    // + CRUD stuff I suppose
}

How can I deal with having different Question models? Are Eloquent models not inherently tied to a particular table?

I have for example a SQLQuestion (where the logic would simply execute a stored SQL statement pulled from some lookup table and return the response) and a TimeFrameQuestion (whose logic requires calls to some TimeFrame modules).

The only table TimeFrameQuestion could be pulled from is the general Question table since it has no direct relation to any other table.

Is it possible to have 2 models both look at the Question table without the SQLQuestion collection also containing all the records that are of TimeFrameQuestion type and vice versa?

Upvotes: 2

Views: 491

Answers (1)

OGHaza
OGHaza

Reputation: 4795

I came to realise that I was probably approaching the problem from the wrong direction. Rather than some sort of model inheritance I probably needed controller inheritance instead.

I gave my Question model a handle function which is called by the API, this function instantiates a new controller based on the QuestionType column of the model, calls an ask function and returns the result:

class Question extends Model
{
    protected $table = 'Question';

    protected $fillable = [
        'Statement',
        'QuestionType'
    ];

    public function handle($parameters) {
        $class = '\\App\\Modules\\QAndA\\' . $this->QuestionType . 'Controller';
        $controller = new $class;

        return $controller->ask($this->id, $parameters);
    }
}

These controllers (e.g. SQLQuestionController, TimeframeQuestionController) all extend a QuestionController that defines various shared functionality and the individual controllers override whatever they need to.

Upvotes: 1

Related Questions