Using OPcache to speed up your CLI scripts

With PHP 7 it is now possible to use OPcache efficiently. It can be configured to store the compiled byte code on disk and use it on the next run of a script. Complex command line scripts like Composer and PHPUnit tests will benefit from such a cache as it reduces startup time dramatically.

In addition to benefiting cli scripts, this cache is also used as second level cache in general. This should increase performance if the SHM backed OPcache runs out of memory or the PHP process gets restarted.

To enable the second level cache simply ensure the following ini directives are set:

In this case I am going to store the byte code in /tmp which means it wont survive a reboot and will be kept in RAM by default. We now need to ensure that the mentioned directory /tmp/php-opcache is created by systemd on boot. Place the following content in a file called /etc/tmpfiles.d/php-cli-opcache.conf:

d /tmp/php-opcache 1777 root root 1d

This will also prune all files that are older than one day. You might want to adjust these values to your needs or even use a persistent storage in /var/tmp instead of /tmp.
To initially create this folder simply run

# systemd-tmpfiles --create /etc/tmpfiles.d/php-cli-opcache.conf

You may now check your configuration by running some cli scripts:

$ composer -V

The compiled byte code should now appear in /tmp/php-opcache:

$ tree /tmp/php-opcache               
├── 896f8ffaef254102552141eb4ab1b214
│   └── usr
│       └── bin
│           └── composer.bin
└── 896f8ffaef254102552141eb4ab1b214phar:
    └── usr
        └── bin
            └── composer
                ├── bin
                │   └── composer.bin
                ├── src
                │   ├── bootstrap.php.bin
                │   └── Composer
                │       ├── Command
                │       │   ├── AboutCommand.php.bin
                │       │   ├── ArchiveCommand.php.bin
                │       │   ├── ClearCacheCommand.php.bin