jeudi 3 janvier 2019

Using models vs creating and binding classes

I do not understand the idea of binding classes in service provider. I read articles about Laravel service providers and containers. I understand that Service Provider is a way to organize service objects bindings to the IoC, useful when your application is fairly large. Let's look at this case. I created 4 classes:

class Person
{
    public $name;
    public $surname;

    public function __construct($name, $surname)
    {
        $this->name = $name;
        $this->surname = $surname;
    }

  }


class Car
{

public $model;


public function __construct($model)
{
    $this->model = $model;
}
}


class Adres
{

    public function __construct($street, $city)
    {
        $this->street = $street;
        $this->city = $city;
    }

}

class PremiumClient
{

    public function __construct(Person $p, Car $c, Adres $a)
    {
        $this->person = $p;
        $this->car = $c;
        $this->adres = $p;
    }
}

As you can see I'm trying to inject three dependencies to PremiumClient class. I can achvieve it creating 4 models join them using eloquent relationship. So why is it recommended to bind classes in service provider like this:

class AppServiceProvider extends ServiceProvider
{

    public function boot()
    {
        Schema::defaultStringLength(191);
        $this->app->bind('Car', function ($app, $p) {
            return new Car($p[0]);
        });

        $this->app->bind('Adres', function ($app, $p) {
            return new Adres($p[0], $p[1]);
        });

        $this->app->bind('Person', function ($app, $p) {
            return new Person($p[0], $p[1]);
        });

        $this->app->bind('Premium', function ($app, $p) {
            return new Premium(App::make('Person'),App::make('Car'),App::make('Adres'));
        });
}

I'm not able to understand what are the benefits of binding classes when you can use models to achieve the same goal. When should I use models, and when create class and bind it? Please help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire