-
Notifications
You must be signed in to change notification settings - Fork 1
NamedClosure
The NamedClosure
class is used to wrap closures, to be able to describe them and easily identify them again later. It can be used as a direct replacement of the PHP native Closure class.
$closure = NamedClosure::fromClosure(
function() {
// do something
},
'ID or descriptive text of the closure'
);
Simply check if the callable is a named closure:
if($callable instanceof NamedClosure) {
$origin = $callable->getOrigin();
}
The class comes with a few factory methods to work with common callable types.
$closure = NamedClosure::fromArray(array('ClassName', 'staticMethodName'));
// Description text will be "ClassName::staticMethodName()"
With a custom origin description:
$closure = NamedClosure::fromArray(array('ClassName', 'staticMethodName', 'Comes from here'));
// Description text will be "Comes from here"
$closure = NamedClosure::fromObject($object, 'methodName');
// Description text will be "ObjectClassName->methodName()"
With a custom origin description:
$closure = NamedClosure::fromObject($object, 'methodName', 'Comes from here');
// Description text will be "Comes from here"
$closure = NamedClosure::fromClosure(
function() {
// do something
},
'Closure description text'
);
The fromObject()
method cannot be used with private object methods.
This is because the Closure::fromCallable()
method must be called
from the class containing the target method for it to work.
This can be easily circumvented to keep the class and method name as description of the closure:
class ExampleClass
{
public function createCallable()
{
// Create the callable array
$callback = array($this, 'doSomething');
return NamedClosure::fromClosure(
Closure::fromCallable($callback), // To call the private method
ConvertHelper::callback2string($callback) // Set the description
);
}
private function doSomething() : void
{
}
}
NOTE: The ConvertHelper::callback2string() works even if the target method is not callable (which is the case here with a private method). This guarantees that the description is always meaningful.
If all closures are created using the named closure wrapper, they will automatically be recognized by all helpers in the package.
For example, the convert helper's callback2string()
method:
use AppUtils;
class ExampleObjectCallback
{
public function doSomething() : void
{
}
);
$example = new ExampleObjectCallback();
$closure = NamedClosure::fromObject($example, 'doSomething');
echo ConvertHelper::callback2string($closure);
This will output the following string:
Closure:ExampleObjectCallback->doSometing();
New here?
Have a look at the overview for a list of all helper classes available in the package.
Table of contents
Find the current page in the collapsible "Pages" list above, and expand the page, to view a table of contents.