Support for closures
softius opened this issue · comments
The documentation does not mention anything about closures but it appears that those are supported by InMemoryQueue. Please consider the following scenario:
$queue = new InMemoryQueue();
$queue->push(function() {
return 'Example with closures';
});
$item = $queue->pop();
echo $item();
The above scenario is executed successfully, printing "Example with closures". Some other Queue Types may not support this directly, but we can serialise closures using jeremeamia/SuperClosure library.
Are there any plans to support closures?
Closures are supported in InMemoryQueue
only because it's not a persistent queue. For any other queue you indeed have to serialize closure before inserting. So you can do something like this:
// if the queue does not support object types,
// wrap it with TypeSafeQueue decorator:
// $queue = new TypeSafeQueue($queue);
$item = new SerializableClosure(function() {
return 'Example with closures';
});
$queue->push($item);
It's also quite trivial to create a decorator which will wrap closures automatically:
class SuperTypeSafeQueue extends TypeSafeQueue
{
public function push($item, $eta = null)
{
if ($item instanceof \Closure) {
$item = new SerializableClosure($item);
}
parent::push($item, $eta);
}
}
Now you can pass them directly, just like in your example:
$queue = new SuperTypeSafeQueue($queue);
$queue->push(function() {
return 'Example with closures';
});
Closing this, as I don't think it worth adding extra dependencies to the library for such a simple use case. Moreover, the solution is really trivial to implement for ones who still need to pass closures directly.