phroute
phroute copied to clipboard
Cache problem with closures
Hi, When I try to cache route data array, I get this error: Exception: Serialization of 'Closure' is not allowed That's why the filters are also included in the array! Closures are not normally serializable, and caching can not be done without serializing. Any workarounds? Thanks
One possible solution: don't use anonymous functions in filters.
So, instead of:
$router->filter('statsStart', function(){
setPageStartTime(microtime(true));
});
Try this:
function myFunction() {
setPageStartTime(microtime(true));
}
$router->filter('statsStart', 'myFunction');
Yeah, I see. I searched a bit and found this too:
https://github.com/jeremeamia/super_closure
It's method is slow, unclean and sometimes not safe. Your solution works but I won't use it, since it's not that much object oriented. I think perhaps we can deffer the function assignments to run time? or abstract this kind of login in the controllers somehow. Since I am considering an extendable system, I might switch to aspect oriented programming which might facilitate addressing this problem in the controllers themselves.
Sure, you can just reference a class name or function name as suggested by @kstirn
I usually stick my filters in a class like:
namespace App\Http\Filters;
class AuthFilter {
public function filter(){
}
}
// Then use...
$router->filter('auth', ['App\\Http\\Filters\\AuthFilter', 'filter']);