How to Inherit Models in Laravel 4

Asked

Viewed 1,147 times

0

Whereas you have the Models Pessoa and Usuario, and that a Usuario is a Pessoa (Usuario extends Pessoa), or Usuario belongsTo Pessoa and Pessoa hasOne Usuario.

It is possible that the Usuario has the same attributes and methods as Pessoa without doing $usuario->pessoa->metodo, simply making $usuario->metodo?

  • is ratio 1 to 1? you want to ?

  • The relationship I know how to do, but I wish I could use class inheritance ...

  • got it !!!!!!!!!!

  • Look I’d need to test the behavior because there are two models neh by your question !!!

  • 1

    the two already inherit from the Eloquent correct that statement? if it is not gives!

2 answers

3


It doesn’t work that way in Laravel.

Relationships are represented as follows (in your case):

class Usuario extends Eloquent {
    public function belongsTo()
    {
        return $this->belongsTo('Usuario');
    }
}

class Pessoa extends Eloquent {
    public function hasOne()
    {
        return $this->hasOne('Usuario');
    }
}

Regarding methods and/or properties, you have access to all of the related object (Eloquent) but referring to the Eloquent/Model.

If you want to do something more specific, you should use the concepts/methodologies related to:

  • Addiction Injection (DI)
  • Ioc
  • S.O.L.I.D

For example, working with Repositories (Repositories/Factories), as almost everything is isolated from the basic structure (mvc), you will have for example "n" repositories with the necessary methods/linked to any class, with this you can access them from any "place".

I believe that by researching the above concepts you will get to where you want.

I recommend purchasing a subscription to Laracasts of the amazing Jeffrey Way.

0

Consider that relationship is not the same thing as inheritance, when you define relationship between models, it has nothing to do with inheritance of methods and attributes.

To create inheritance between models, you need to extend them in this way:

class Evento{
     var $table = 'eventos';
}

class Reuniao extends Evento{

}
  • 2

    Then it does not work, if it extends from another class, it does not give, consider that I did not extend Eloquent Event.

  • But it can create a composition and share methods between classes, right?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.