Jens Segers on Oct 31 2015

Clearing PHP's OPcache with CacheTool

OPcache is great, it improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request.

But it seems like sometimes OPcache is not refreshing updated files in its cache, or that it cached a broken version of the compiled.php file because a user visited the website while Laravel was generating it.

To fix this issue, I'm now using CachTool to clear the OPcache on every deploy automatically.

First download the cachetool.phar file or install it globally using composer:

composer global require gordalina/cachetool

By default, CacheTool will try to connect to FastCGI on port 9000. So if your PHP installation is not using a socket, you can just run:

cachetool opcache:reset

But in case you are using sockets (most likely), you need to pass the socket location to the command:

cachetool opcache:reset --fcgi=/var/run/php5-fpm.sock

And to make sure the OPcache is cleared after each deploy, add the command to your composer post install/update scripts. This way, every time you install your dependencies, OPcache is forced to refresh its cache:

    "post-install-cmd": [
        // ...
        "cachetool opcache:reset --fcgi=/var/run/php5-fpm.sock"
    ]

Comments