G
G
ganjo8882020-01-31 16:07:05
Laravel
ganjo888, 2020-01-31 16:07:05

How to implement DI?

there is an index method in it, I use a third-party class (package) Resolver that accepts Eloquent\Builder . I want to make EloquentResolver through DI.

public function index($argument)
    {
        $resolver = new Resolver(Model::query);
        $result = $resolver->build($argument);

    return $result;
    }

My thoughts, you need to make the interface ResolverInterface declare a public build method there. Write bind ServiceProvider , ResolverInterface::class=> Resolver::class
And in the class itself create __cunstruct(ResolverInterface $resolver) , and use already with $resolver , that's just not clear use it, because I need to pass Eloquent \ Builder
into it. Tell me how it's better to do it, don't judge strictly...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JhaoDa, 2020-01-31
@JhaoDa

DI is not a panacea, therefore:
Resolver.php

public function via(Builder $builder)
{
    $this->builder = $builder;
}

public function build($argument)
{
    $this->builder->where('field', $argument)->...;
}

Service provider
$this->singletons = [
    Resolver::class => Resolver::class
];

Controller
public function __construct(Resolver $resolver)
{
    $this->resolver = $resolver;
}

public function index($argument)
{
    return $resolver->via(Model::query())->build($argument);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question