Installation Add the package via Composer:
composer require hyperf/conditionable
Register the service provider in config/autoload.php (Hyperf):
'providers' => [
Hyperf\Conditionable\ConditionableServiceProvider::class,
],
Basic Usage
Define a conditionable class (e.g., app/Models/ConditionableUser.php):
use Hyperf\Conditionable\Conditionable;
class ConditionableUser extends Conditionable
{
protected $conditions = [
'is_active' => fn ($user) => $user->active,
'is_admin' => fn ($user) => $user->role === 'admin',
];
}
First Use Case Apply conditions in a controller or service:
$users = ConditionableUser::query()
->whereCondition('is_active')
->whereCondition('is_admin')
->get();
Define Conditions
Extend Conditionable and declare conditions as closures or callables:
protected $conditions = [
'has_permission' => fn ($model) => $model->permissions->contains('edit'),
];
Apply Conditions Chain conditions in queries:
$filtered = Model::query()
->whereCondition('has_permission')
->whereCondition('is_verified', true); // Pass args if needed
Reusable Condition Groups Group conditions for modularity:
public function scopeActiveAdmins($query)
{
return $query->whereCondition('is_active')
->whereCondition('is_admin');
}
'is_eligible' => fn ($user) => $user->eligibilityService()->check(),
return $this->filterConditions($users, ['is_active']);
Performance
select() or exists() checks first.Closure Scope Conditions run in the model’s scope. Access other models/services via dependency injection:
protected $conditions = [
'has_order' => fn ($user) => $user->orders()->exists(),
];
Caching Conditions are not cached by default. Cache results if conditions are expensive:
$cached = Cache::remember("user_{$user->id}_conditions", 3600, fn () =>
$user->whereCondition('is_active')
);
'debug_condition' => fn ($model) => logger()->debug('Condition', ['model' => $model->toArray()]),
toSql() to inspect generated queries:
$query = Model::whereCondition('is_active');
logger()->info($query->toSql(), $query->getBindings());
Custom Condition Types
Extend Hyperf\Conditionable\Contracts\Condition for advanced logic:
class CustomCondition implements Condition
{
public function evaluate($model, ...$args) { ... }
}
Global Conditions Register conditions globally in the service provider:
Conditionable::extend('global_condition', fn ($model) => $model->someGlobalCheck());
Condition Validation Validate conditions before query execution:
if (!$this->validateCondition('is_active')) {
throw new \RuntimeException('Invalid condition');
}
How can I help you explore Laravel packages today?