mercredi 25 avril 2018

How to instantiate classes based on type in laravel?

So I have a BaseValuation abstract class and it's implementations example FooValuation and BarValuation.

I want to instantiate Foo or Bar implementations depending on use input. So I created a simple class myself called Valuation which simply does this:

<?php

namespace App\Valuation;

class Valuation
{
    public $class;

    public function __construct($id, $type = 'basic')
    {
        $class = 'App\Valuation\Models\\' . ucfirst($type) . 'Valuation';

        $this->class = new $class($id);
    }

    public function make()
    {
        return $this->class;
    }
}

Using this I can simply do (new App\Valuation\Valuation($id, $type))->make() and I will get the desired implementation according to what the use asked for.

But I know that laravel's container is powerful and must allow me to do this somehow but I cannot understand how this will be done. Any ideas anyone?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire