Service » Query scopes
Define named, reusable filter criteria at the service level and combine them on the fly.
About query scopes
Query scopes let you give meaningful names to commonly used MongoDB filter criteria and keep them in one place — your service class. Once defined, a scope can be retrieved by name and passed directly to any service method that accepts a filter array, or merged with other scopes and ad-hoc criteria using the helper methods below.
Methods
-
getScopes(): array OVERRIDE
Override this
protected staticmethod in your service to define named scopes. Return an associative array where each key is a scope name and the value is a standard MongoDB filter array.The base implementation returns an empty array, so any service that does not override this method simply has no scopes available.
-
scope(string ...$names): array
Returns a merged filter array for one or more named scopes. Unknown scope names are silently ignored. Pass multiple names to combine their filters into a single array.
-
mergeFilters(array ...$filters): array
Merges any number of filter arrays into a single array. Useful for combining the output of
scope()with additional ad-hoc criteria before passing the result to a query method.
Defining scopes
Override getScopes() in your service and return an associative array of named filter
criteria.
<?php
use District5\Mondoc\Db\Service\MondocAbstractService;
class UserService extends MondocAbstractService
{
protected static function getCollectionName(): string
{
return 'users';
}
protected static function getScopes(): array
{
return [
'adults' => ['age' => ['$gte' => 18]],
'active' => ['active' => true],
'premium' => ['plan' => 'premium'],
];
}
}
Using scopes
Single scope
<?php
$filter = UserService::scope('adults');
$adults = UserService::getMultiByCriteria($filter);
Multiple scopes merged
Pass multiple scope names to scope() to merge their filters in one call.
<?php
$filter = UserService::scope('adults', 'active');
$activeAdults = UserService::getMultiByCriteria($filter);
Scope combined with extra criteria
Use mergeFilters() to combine scope output with additional filter criteria.
<?php
$filter = UserService::mergeFilters(
UserService::scope('adults', 'active'),
['country' => 'GB']
);
$gbActiveAdults = UserService::getMultiByCriteria($filter);