A
A
Alexey Verkhovtsev2018-08-24 17:50:58
Laravel
Alexey Verkhovtsev, 2018-08-24 17:50:58

Is it possible to consider a DI container as a kind of factory or what am I doing wrong?

I inject into the controller's constructor and then just call the method.
This is what my service provider looks like

public function register()
    {
        //
        $this->app->bind(CampaignService::class, function($app) {
            $entityManager = $app->make('registry')->getManager();
            $doctrineCampaignRepository = new DoctrineCampaignRepository($entityManager, $entityManager->getRepository(Campaign::class));
            $doctrineCampaignTypeRepository = new DoctrineCampaignTypeRepository($entityManager);
            $doctrineCampaignCategoryRepository = new DoctrineCampaignCategoryRepository($entityManager);
            return new CampaignService($doctrineCampaignRepository, $doctrineCampaignTypeRepository, $doctrineCampaignCategoryRepository);
        });
    }

This is my first time working with service providers and containers, but am I doing it right? Looks like a factory, doesn't it? Or is it the way it is or I'm using it for other purposes, point out the errors, please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Nesmeyanov, 2018-08-24
@seftomsk

The bind method just registers the "factory". Those. each time a service is resolved (received) from the container, it will be created according to the defined scheme.

$container->call(function(CampaignService $c): void {
    echo \spl_object_id($c); // 1
});

$container->call(function(CampaignService $c): void {
    echo \spl_object_id($c); // 2
});

If the service must be constant, then it makes sense to replace bind with singleton
$container->call(function(CampaignService $c): void {
    echo \spl_object_id($c); // 1
});

$container->call(function(CampaignService $c): void {
    echo \spl_object_id($c); // 1
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question