Follow these steps for a laminas-mvc based application:
-
Install laminas-cache and a storage adapter, like
laminas-cache-storage-adapter-filesystem
(if you use the laminas-mvc-skeleton application then both components are automatically registered in the application inconfig/modules.config.php
) -
Extend the configuration of your application. You can use the global application configuration, e.g. the
config/autoload/global.php
file and choose a name for the cache:return [ 'caches' => [ 'default-cache' => [ 'adapter' => Laminas\Cache\Storage\Adapter\Filesystem::class, 'options' => [ 'cache_dir' => __DIR__ . '/../../data/cache', ], ], ], // … ];
-
Now you can fetch the cache by the name
default-cache
from the application service container.Usage in a controller, e.g.
module/Application/src/Controller/IndexController.php
:use Laminas\Cache\Storage\StorageInterface; use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\ViewModel; final class IndexController extends AbstractActionController { private StorageInterface $cache; public function __construct(StorageInterface $cache) { $this->cache = $cache; } public function indexAction(): ViewModel { if (! $this->cache->hasItem('example')) { // … } return new ViewModel(); } }
Create a factory for the controller, e.g.
module/Application/src/Controller/IndexControllerFactory.php
:namespace Application\Controller; use Laminas\Cache\Storage\StorageInterface; use Psr\Container\ContainerInterface; final class IndexControllerFactory { public function __invoke(ContainerInterface $container): IndexController { /** @var StorageInterface $cache */ $cache = $container->get('default-cache'); return new IndexController($cache); } }
Register the factory for the controller, e.g.
module/Application/config/module.config.php
:namespace Application; return [ 'controllers' => [ 'factories' => [ Controller\IndexController::class => Controller\IndexControllerFactory::class, ], ], ];
This all works because both components, laminas-cache and laminas-cache-storage-adapter-filesystem, provide and register factories that use the configuration and look for the configuration keys caches
and cache
.
- use
caches
if you need multiple storage adapters, recommended – also for one adapter - use
cache
if you only need one explicit storage adapter