Answer the question
In order to leave comments, you need to log in
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');
}
}
$service = app()->make(SpiderService::class); // ???????
Answer the question
In order to leave comments, you need to log in
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);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question