Resolving service based on model in AppServiceProvider

I had an idea overnight to make service which keeps all the matchers. The only downside to this solution is injecting every matcher.

class ConditionResolver implements ConditionResolverInterface
{
    /** @var ConditionMatcherInterface[] */
    private $conditionMatchers = [];

    public function __construct(
       DateConditionMatcher $dateConditionMatcher, 
       TimeConditionMatcher $timeConditionMatcher,
       LocationConditionMatcher $locationConditionMatcher
    ) {
       $this->conditionMatchers[DateCondition::class] = $dateConditionMatcher;
       $this->conditionMatchers[TimeCondition::class] = $timeConditionMatcher;
       $this->conditionMatchers[LocationCondition::class] = $locationConditionMatcher;
    }
}

so now I am able to use correct matcher to given condition in this way(simplified):

foreach ($model->conditions as $condition)
{
    $this->conditionMatchers[get_class($condition)]->match($condition, $request);
}

It allows me to inject various of services into that matchers in AppServiceProvider.

$this->app->singleton(LocationServiceInterface::class, function($app){
   return new LocationService();
});

$this->app->singleton(DateConditionMatcher::class, function($app){
   return new DateConditionMatcher();
});

$this->app->singleton(TimeConditionMatcher::class, function($app){
   return new TimeConditionMatcher();
});

$this->app->singleton(LocationConditionMatcher::class, function($app){
    return new LocationConditionMatcher($app->make(LocationServiceInterface::class));
});

Overall I think I miessed something and it would be done in more elegant way, but for now I treat it as an answer. If you have better solution, please share 🙂

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top