jeudi 12 octobre 2017

Laravel extend or use Traits dynamically

It is possible to extend or use different class during run time?

Example: Let say we have a model called Player (Our A -model)

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Player extends Model{

}

And we have 2 other models (B and C models)

<?php
    namespace App\Models;
    use Illuminate\Database\Eloquent\Model;

    protected $connection= 'db_b';

    class PlayerInfoB extends Model{
        function getName(){
            return $this->name;
        }
    }

Our C model

<?php
        namespace App\Models;

        use Illuminate\Database\Eloquent\Model;

        protected $connection= 'db_c';

        class PlayerInfoC extends Model{
            function getName(){
                return $this->name_g;
            }
        }

How Model A (Player) can extend Model B or C during run time based on configuration or other data

Why I need this. I have a 2 or more different tables, this tables columns have different names, so for example:

Table 1 - name

Table 2 - name_g

Table 3 - name_full

So I need a wrapper that I can always call getName(), without checking what table is used now.

$player = Player::get();

echo $player->getName();

If something is not clear, please comment and I will update my question.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire