phroute icon indicating copy to clipboard operation
phroute copied to clipboard

Cache problem with closures

Open creativefctr opened this issue 9 years ago • 3 comments

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

creativefctr avatar Nov 15 '15 16:11 creativefctr

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');

kstirn avatar Nov 20 '15 18:11 kstirn

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.

creativefctr avatar Nov 20 '15 22:11 creativefctr

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']);

mrjgreen avatar Dec 27 '15 23:12 mrjgreen