Reputation: 7587
some packages comes pre-packed with its own models ex.Cart
but sometimes i want to add some extra logic to that model,
so instead of editing the original model or searching everywhere where this model was used and replace it with the newly created one,
i thought i would use app bind ex.
// model
<?php
namespace App\Binders;
use some\package\Models\Cart;
class CartBinder extends Cart
{
// extra logic
}
// AppServiceProvider@register
$this->app->bind('some\package\Models\Cart', 'App\Binders\CartBinder');
but sadly this has no effect & am not sure what i've missed :(.
Upvotes: 2
Views: 2354
Reputation: 41
I'll suggest you decorate the model using the Decorator pattern. Jeff Way has a good series Design Patterns or check this decorator pattern example. It could go along the line:
<?php
namespace App\Binders;
use some\Package\Models\Cart;
class CartBinder
{
protected $cart;
public function __contruct(Cart $cart)
{
$this->cart = $cart;
}
// the extra logic
}
Then You can bind the dependencies in the Service Container.
$this->app->bind('App\Binders\CartBinder', function ($app) {
return new \App\Binders\CartBinder(new some\Package\Models\Cart);
});
From there you can resolve it, instantiate somewhere in your code (controllers, models...) this way:
$cart = $this->app->make('App\Binders\CartBinder');
Or you could inject in your controller's method.
// use App\Binders\CartBinder;
// ...
public function store(CartBinder $cart)
{
// ...
}
Upvotes: 2