Installation
composer require toflar/fast-set
Register the service provider in config/app.php (if not auto-discovered):
'providers' => [
Toflar\FastSet\FastSetServiceProvider::class,
],
Basic Usage Create a precompiled set from an array:
use Toflar\FastSet\Facades\FastSet;
$set = FastSet::create(['apple', 'banana', 'cherry']);
$exists = $set->contains('banana'); // Returns true instantly
First Use Case Optimize a Laravel request filter or validation rule:
$allowedRoles = FastSet::create(['admin', 'editor', 'viewer']);
if ($allowedRoles->contains(auth()->user()->role)) {
// Proceed with elevated permissions
}
Precompiled Sets for Performance Use in high-frequency checks (e.g., route middleware, API rate limiting):
$rateLimitedIps = FastSet::create(explode(',', config('rate_limit.ips')));
if ($rateLimitedIps->contains(request()->ip())) {
abort(429);
}
Caching Layer Integration Cache precompiled sets to avoid recompilation:
$cachedSet = Cache::remember('user_roles_set', now()->addHour(), function () {
return FastSet::create(User::pluck('role')->unique()->toArray());
});
Laravel Collections Extension
Add a toFastSet() method to collections:
// In a Collection macro (e.g., in AppServiceProvider)
collect(['a', 'b', 'c'])->macro('toFastSet', function () {
return FastSet::create($this->all());
});
$activeUserIds = User::where('active', true)->pluck('id')->toFastSet();
@set directive for template checks:
// In AppServiceProvider
Blade::directive('set', function ($expression) {
return "<?php echo (Toflar\FastSet\Facades\FastSet::create({$expression})->contains(" . $expression[1] . ")) ? 'true' : 'false'; ?>";
});
$subscribers = FastSet::create(config('event.subscribers'));
if ($subscribers->contains($eventName)) {
// Dispatch event
}
Memory vs. Speed Tradeoff
in_array() instead.Immutable After Creation
$set = $set->merge(['new_item']); // Returns a new set
Serialization Issues
getArrayCopy():
$array = $set->getArrayCopy();
Case Sensitivity
$set = FastSet::create(['Apple', 'Banana'], true); // Second arg = case-insensitive
$set->isCompiled(); // Returns true if optimized
unset() to free memory when done:
unset($largeSet);
FastSet::hash(function ($item) {
return md5(serialize($item));
});
$proxy = new class($dataLoader) implements \ArrayAccess {
public function offsetExists($offset) {
return FastSet::create($this->loadData())->contains($offset);
}
// ...
};
FastSet class to support cache storage:
class CachedFastSet extends \Toflar\FastSet\FastSet {
public function __construct(string $cacheKey, array $data = []) {
parent::__construct($data);
Cache::put($cacheKey, $this);
}
}
How can I help you explore Laravel packages today?