How to make models inheritance in Laravel 4

0

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

Can Usuario have the same attributes and methods of Pessoa without doing $usuario->pessoa->metodo , simply doing $usuario->metodo ?

    
asked by anonymous 03.07.2014 / 22:38

2 answers

3

It does not work like that 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');
    }
}

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

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

  • Dependency Injection (DI)
  • IoC
  • S.O.L.I.D

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

I think that by researching the above concepts you will be able to get where you want.

I recommend purchasing a Laracasts from the incredible Jeffrey Way .

    
04.07.2014 / 00:22
0

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

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

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

class Reuniao extends Evento{

}
    
03.07.2014 / 22:48