P
P
part_os2018-10-28 21:45:06
Laravel
part_os, 2018-10-28 21:45:06

How to bind a service and an interface with multiple implementations?

Good evening, tell me how to connect the service with the interface, and several implementations.
For example:

class SpiderService
{ 
 /**
     * SpiderService constructor.
     * @param AuctionRepositoryInterface $auctionRepository
     */
    public function __construct(AuctionRepositoryInterface $auctionRepository)
    {
        $this->auctionRepository = $auctionRepository;
    }
}

interface AuctionRepositoryInterface
{
    public function getActualDateAuctions();
}

class AuctionRepository implements AuctionRepositoryInterface
{
public function getActualDateAuctions()
    {
           //реализация
     }
}

class InMemoryAuctionRepository implements AuctionRepositoryInterface
{
 public function getActualDateAuctions()
    {
         //какая то реализация
    }
}

class SpiderServiceProvider extends ServiceProvider
{

    public function register()
    {
        $this->app->singleton('spider', 'App\Services\SpiderService');
    }
}

And how to call a service with a different implementation?
$service = app()->make(SpiderService::class);    // ???????

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill Nesmeyanov, 2018-10-29
@part_os

This is done via contextual binding ( https://laravel.com/docs/5.7/container#contextual-...

// Когда SpiderService требует интерфейс AuctionRepositoryInterface, 
// то мы даём ему InMemoryAuctionRepository
$app->when(SpiderService::class)
   ->needs(AuctionRepositoryInterface::class)
   ->give(InMemoryAuctionRepository::class);

// Когда Someone требует интерфейс AuctionRepositoryInterface, 
// то мы даём ему AuctionRepository
$app->when(Someone::class)
   ->needs(AuctionRepositoryInterface::class)
   ->give(AuctionRepository::class);

// Во всех остальных случаях мы предоставляем AnotherRepository
$app->singleton(AuctionRepositoryInterface::class, AnotherRepository::class);

Be careful, because contextual binding does not work in case of injection through methods ($container->call), but only through the constructor.

E
Eugene, 2018-10-28
@Nc_Soft

https://laravel.com/docs/5.0/container#binding-int...
look at $app->bind, that's where the binding goes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question