mardi 4 septembre 2018

Get instance of model depending on the type

I have two kinds of notes: ReferenceNote and TaskNote. They both inherited from BaseNote.

When I create new note I have type in request and depending on that type I create corresponding model.

But how can I get corresponding model when I need to get note by id?

My current solution:

$base_note = BaseNote::find($id);

$note = $note_factory->getNote($base_note);

In Factory:

function getNote(BaseNote $base_note) {
    if ($base_note->type === self::REFERENCE_NOTE_TYPE) {
        $note = new ReferenceNote($base_note->getAttributes());
        //logic of adding additional attributes for reference note
    } else {
        $note = new TaskNote($base_note->getAttributes());
        //logic of adding additional attributes for task note
    }
}

Is there a better way of doing this?

Aucun commentaire:

Enregistrer un commentaire