Search code examples
phpsymfonysymfony-cache

Pass parameters to Symfony's $cache->get()


I am afraid I have a beginners PHP question. I am using Symfony's Cache component. https://symfony.com/doc/current/components/cache.html

I am calling the cache object inside of a function which receives 2 arguments ($url, $params).

class MainController extends AbstractController {
    public function do($url, $params) {
        $cache = new FilesystemAdapter();
        return $cache->get('myCacheName', function (ItemInterface $c) {
            global $url;
            var_dump($url); // ---> null !!!!
        }
    }
}

My problem is, that I cannot access the function arguments inside of the cache method call. $url and $params is null. Of course I could use public class variables in class MainController to send the variables back ad forth, but this seems to be a bit clumsy.


Solution

  • In PHP a closure does not have access to variables outside of its scope by default, you have to use those like so:

    return $cache->get('myCacheName', function (ItemInterface $c) use ($url) {
        var_dump($url); // ---> no longer null !!!!
    }