note 105261 added to functions.anonymous
| From: | simon at generalflows dot com | Date: | Fri, 05 Aug 2011 15:23:52 +0000 |
| Subject: | note 105261 added to functions.anonymous | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-182262@lists.php.net to get a copy of this message | ||
<?php
/*
* An example showing how to use closures to implement a Python-like decorator
* pattern.
*
* My goal was that you should be able to decorate a function with any
* other function, then call the decorated function directly:
*
* Define function: $foo = function($a, $b, $c, ...) {...}
* Define decorator: $decorator = function($func) {...}
* Decorate it: $foo = $decorator($foo)
* Call it: $foo($a, $b, $c, ...)
*
* This example show an authentication decorator for a service, using a simple
* mock session and mock service.
*/
session_start();
/*
* Define an example decorator. A decorator function should take the form:
* $decorator = function($func) {
* return function() use $func) {
* // Do something, then call the decorated function when needed:
* $args = func_get_args($func);
* call_user_func_array($func, $args);
* // Do something else.
* };
* };
*/
$authorise = function($func) {
return function() use ($func) {
if ($_SESSION['is_authorised'] == true) {
$args = func_get_args($func);
call_user_func_array($func, $args);
}
else {
echo "Access Denied";
}
};
};
/*
* Define a function to be decorated, in this example a mock service that
* need to be authorised.
*/
$service = function($foo) {
echo "Service returns: $foo";
};
/*
* Decorate it. Ensure you replace the origin function reference with the
* decorated function; ie just $authorise($service) won't work, so do
* $service = $authorise($service)
*/
$service = $authorise($service);
/*
* Establish mock authorisation, call the service; should get
* 'Service returns: test 1'.
*/
$_SESSION['is_authorised'] = true;
$service('test 1');
/*
* Remove mock authorisation, call the service; should get 'Access Denied'.
*/
$_SESSION['is_authorised'] = false;
$service('test 2');
?>
----
Server IP: 69.147.83.197
Probable Submitter: 91.125.191.199
----
Manual Page -- http://www.php.net/manual/en/functions.anonymous.php
Edit -- https://master.php.net/note/edit/105261
Del: integrated -- https://master.php.net/note/delete/105261/integrated
Del: useless -- https://master.php.net/note/delete/105261/useless
Del: bad code -- https://master.php.net/note/delete/105261/bad+code
Del: spam -- https://master.php.net/note/delete/105261/spam
Del: non-english -- https://master.php.net/note/delete/105261/non-english
Del: in docs -- https://master.php.net/note/delete/105261/in+docs
Del: other reasons-- https://master.php.net/note/delete/105261
Reject -- https://master.php.net/note/reject/105261
Search -- https://master.php.net/manage/user-notes.php