I am new to Laminas, I need to know how Cache works

If anybody provides a complete working example, I’ll appreciate.

Hello and welcome to our forums! :smiley:

Before starting, make sure a cache adapter is installed, like the APCu or the Filesystem adapter.

Here is an example which uses two different cache adapters as storage for the cache:

require_once __DIR__ . '/vendor/autoload.php';

$config = (new Laminas\ConfigAggregator\ConfigAggregator([
    Laminas\Cache\ConfigProvider::class,
    Laminas\Cache\Storage\Adapter\BlackHole\ConfigProvider::class,
    Laminas\Cache\Storage\Adapter\Memory\ConfigProvider::class,
]))->getMergedConfig();

$container = new Laminas\ServiceManager\ServiceManager($config['dependencies']);

/** @var Laminas\Cache\Service\StorageAdapterFactoryInterface $storageFactory */
$storageFactory = $container->get(
    Laminas\Cache\Service\StorageAdapterFactoryInterface::class
);

$storage1 = $storageFactory->create(Laminas\Cache\Storage\Adapter\BlackHole::class);
$storage2 = $storageFactory->create(Laminas\Cache\Storage\Adapter\Memory::class);

$storage1->setItem('key', 'value');
if ($storage1->hasItem('key')) {
    echo $storage1->getItem('key'); // "value"
}

$storage2->setItem('key', 'value');
if ($storage2->hasItem('key')) {
    echo $storage2->getItem('key'); // "value"
}

Check also the quick start and the example section:

Thank you froschdesign, Actually I am very beginner and could not get how to implement the code you provided.

  1. I am using php 8 and APCu is for older php versions. I have to cache DB results for like 10 minutes. what is the best adapter you suggest?

  2. I have installed Filesystem and here is require section of my composer.json.

“laminas/laminas-cache”: “*”,
“laminas/laminas-cache-storage-adapter-filesystem”: “^2.0”,
“laminas/laminas-config-aggregator”: “^1.7”

  1. here is the error I am getting

Class Application\Model\Laminas\ConfigAggregator\ConfigAggregator not found

Thank you,
Irfan

Dear @irfan,

Your problem is that you’ve not used your class correctly. So, some basic usage explanation here. When using a class of any third-party library you can use it in two ways. Here is an example.

<?php

namespace Application\Model;

use Laminas\ConfigAggregator\ConfigAggregator;

class MyModel {
    public function __constructor(){
       $configObject = new ConfigAggregator();
    }
}
/** Second way to use it is to use the complete namespace with a backslash and that is your problem. */

namespace Application\Model;
 
class MyModel {
    public function __constructor(){
       $configObject = new \Laminas\ConfigAggregator\ConfigAggregator;
    }
}

I hope it helps. Also, the working example given is for core PHP(without any framework) and you’re using the MVC application of Laminas. Therefore, things change in the MVC version compared to using your own constructed framework. The above example will most likely work in WordPress. Thanks!

Thank you ALTAMASH, I will try this.

My code example is independent of an application and therefore the ConfigAggregator is used. In a laminas-mvc or Mezzio application this is not needed!
Do use laminas-cache as stand-alone solution or do you have an application based on laminas-mvc or Mezzio?

Check also the documentation of PHP for the basics of namespaces.

Yes my Application is based on laminas-mvc and I want o implement laminas cache in it. thanks

Follow these steps for a laminas-mvc based application:

  1. 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 in config/modules.config.php)

  2. 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',
                ],
            ],
        ],
        // …
    ];
    
  3. 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