Important

You are browsing the documentation for version 3.1 of OroCommerce, OroCRM and OroPlatform, which is no longer maintained. Read version 5.1 (the latest LTS version) of the Oro documentation to get up-to-date information.

See our Release Process documentation for more information on the currently supported and upcoming releases.

OroCommerce Render Cache Extension

One of the ways to significantly improve website performance is to enable caching. OroCommerce Render Cache Extension provides the server-side cache for OroCommerce storefront layouts. With a few layout-block options, you can enable cache for specific layout blocks permanently or for a particular time and invalidate it with the cache tags from a regular Symfony service when needed. The extension also supports complex caching strategies using the custom cache metadata provider PHP class.

Installation

  1. Install the extension using the composer:

    composer require oro/layout-cache
    
  2. Clear the application cache:

    php bin/console cache:clear --env=prod
    

Cache Layout Blocks

To cache a block in the layout tree, you have to provide cache metadata with the cache block option.

Note

Layout block cache does not support blocks that were rendered using iteration over data, because it relies on a block id that is reused multiple times when iteration over data is used.

Enable the Cache

To enable the layout block cache, provide the cache block option.

cache: true means the block is cached forever

1layout:
2  actions:
3    - '@setOption':
4        id: <block-id>
5        optionName: cache
6        optionValue: true

Disable the Cache

By default, the cache is disabled for all the blocks. You can also disable the cache enabled by another layout update.

1layout:
2  actions:
3    - '@setOption':
4        id: <block-id>
5        optionName: cache
6        optionValue: null

Configuration Reference

maxAge

type: `integer` optional, default: null

Indicates how long the block can be cached. To make the block always return the fresh content, you can set maxAge to 0 (it is used for post-cache substitution).

For example, store the cache item for 10 minutes:

1layout:
2  actions:
3    - '@setOption':
4        id: <block-id>
5        optionName: cache
6        optionValue:
7          maxAge: 600

varyBy

type: `array of scalar items` optional, default: []

Defines the items that the block cache varies by (e.g., product id, whether the user is logged in or not).

For example, vary the cache item by a product id:

1layout:
2  actions:
3    - '@setOption':
4        id: <block-id>
5        optionName: cache
6        optionValue:
7          varyBy:
8            product: '=data["product"].getId()'

tags

type: `array of scalar items` optional, default: []

Cache tags provide a way to track which cache items depend on certain data. Tags are used for the cache invalidation.

For example tag the cache item with a product id:

1layout:
2  actions:
3    - '@setOption':
4        id: <block-id>
5        optionName: cache
6        optionValue:
7          tags:
8            - '="product_" ~data["product"].getId()' # For product with id = 14 it's evaluated to `product_14`

if

type: `boolean` optional, default: true

Indicates when the cache must be enabled.

For example, enable the cache only for not logged in users:

1layout:
2  actions:
3    - '@setOption':
4        id: <block-id>
5        optionName: cache
6        optionValue:
7          if: '=!context["is_logged_in"]'

Note

All the options can apply layout expressions and must be evaluated to scalar values. Also, layout expressions for the cache option must not depend on other block options.

Layout Update Example

Cache the layout block with the product_view_container id for anonymous users for 10 minutes. The cache varies for different products and is tagged with the product_ID tag:

src/AcmeDemoBundle/Resources/views/layouts/default/oro_product_frontend_product_view/cache_product_view.yml
 1layout:
 2  actions:
 3    - '@setOption':
 4        id: product_view_container
 5        optionName: cache
 6        optionValue:
 7          maxAge: 600                                  # Cache the block for 600 seconds (10 minutes)
 8          if: '=!context["is_logged_in"]'               # Enable cache only when user is not logged in
 9          varyBy:
10            product: '=data["product"].getId()'        # Cache varies per product
11          tags:
12            - '="product_" ~data["product"].getId()'   # Tag is used to invalidate the cache
13                                                       # when required, by calling the `invalidateTags()` method
14                                                       # on the `@cache.oro_layout.render` service

Note

You can use layout update conditions to set cache options depending on the context. For example:

layout:
  actions:
    # ...
  conditions: 'context["is_logged_in"]'

Post-Cache Substitution

Post-cache substitution allows you to cache a block but substitute sub-block content dynamically, or cache a sub-block with different settings.

For example:

  • Cache the whole product_view_container block forever, but render the product_price_container block dynamically:

    src/AcmeDemoBundle/Resources/views/layouts/default/oro_product_frontend_product_view/cache_product_view.yml
     1layout:
     2  actions:
     3    - '@setOption':
     4        id: product_view_container
     5        optionName: cache
     6        optionValue:
     7          varyBy:
     8            product: '=data["product"].getId()'
     9    - '@setOption':
    10        id: product_price_container
    11        optionName: cache
    12        optionValue:
    13            varyBy:
    14              product: '=data["product"].getId()'
    15            maxAge: 0 # force disable the cache for a child block
    
  • Cache the whole product_view_container block for 1 day, but the product_price_container block only for 15 minutes:

    src/AcmeDemoBundle/Resources/views/layouts/default/oro_product_frontend_product_view/cache_product_view.yml
     1layout:
     2  actions:
     3    - '@setOption':
     4        id: product_view_container
     5        optionName: cache
     6        optionValue:
     7          varyBy:
     8            product: '=data["product"].getId()'
     9            maxAge: 86400 # 1 day in seconds
    10    - '@setOption':
    11        id: product_price_container
    12        optionName: cache
    13        optionValue:
    14            varyBy:
    15              product: '=data["product"].getId()'
    16            maxAge: 900 # cache a child block only for 15 minutes
    

Cache Block Visibility

For security reasons, block visibility is not cached. If you do not want to calculate block visibility every time, override it to the static value with the layout update or cache a wrapping container instead.

1layout:
2  actions:
3    - '@setOption':
4        id: product_view_container
5        optionName: visible
6        optionValue: true
7  conditions: 'context["is_logged_in"]'

Make Cache Items Always Vary By Some Data

Out of the box, all cache items vary by localization, theme, and website.

To add additional data to all varyBy cache items, create a service that implements the Oro\Bundle\LayoutCacheBundle\Cache\Extension\RenderCacheExtensionInterface interface and mark it with the layout_cache.extension DI tag.

For example, vary all the cache items by a day of the week:

src/AcmeDemoBundle/Cache/Extension/DayOfWeekExtension.php
 1<?php
 2
 3namespace AcmeDemoBundle\Cache\Extension;
 4
 5use Oro\Bundle\LayoutCacheBundle\Cache\Extension\RenderCacheExtensionInterface;
 6
 7class DayOfWeekExtension implements RenderCacheExtensionInterface
 8{
 9    public function alwaysVaryBy(): array
10    {
11        return ['day_of_week' => date('l')];
12    }
13}
src/AcmeDemoBundle/Resources/config/services.yml
1services:
2  AcmeDemoBundle\Cache\Extension\DayOfWeekExtension:
3    tags: [layout_cache.extension]

Cache Layout Blocks with PHP

Sometimes, layout updates are not flexible enough to cover all the cases with the block caching. In this case, you can create a custom metadata provider service that implements the Oro\Bundle\LayoutCacheBundle\Cache\Metadata\CacheMetadataProviderInterface interface and mark it with the layout_cache.metadata_provider DI tag.

For example, disable the cache for all the blocks if the user is logged in:

src/AcmeDemoBundle/Cache/Metadata/DisableCacheForLoggedInUsersCacheMetadataProvider.php
 1<?php
 2
 3namespace AcmeDemoBundle\Cache\Cache\Metadata;
 4
 5use Oro\Bundle\LayoutCacheBundle\Cache\Metadata\CacheMetadataProviderInterface;
 6use Oro\Bundle\LayoutCacheBundle\Cache\Metadata\LayoutCacheMetadata;
 7use Oro\Component\Layout\BlockView;
 8use Oro\Component\Layout\ContextInterface;
 9
10class DisableCacheForLoggedInUsersCacheMetadataProvider implements CacheMetadataProviderInterface
11{
12    public function getCacheMetadata(BlockView $blockView, ContextInterface $context): ?LayoutCacheMetadata
13    {
14        if (!$context->get('is_logged_in')) {
15            # Do nothing if the user is not logged in
16            return null;
17        }
18
19        # Return cache metadata with max age equal to 0, if the user is logged in
20        return (new LayoutCacheMetadata())->setMaxAge(0);
21    }
22}
src/AcmeDemoBundle/Resources/config/services.yml
1services:
2  AcmeDemoBundle\Cache\Cache\Metadata\DisableCacheForLoggedInUsersCacheMetadataProvider:
3    tags: [layout_cache.metadata_provider]

Invalidating Cache by Tags

To invalidate tagged cache items, you have to call the invalidateTags() method of the @oro.layout_cache.tag_aware_cache_adapter service.

For example, let’s invalidate a cache for a block that depends on a specific product information when product has been updated:

  1. Tag the block that renders product information

    src/AcmeDemoBundle/Resources/views/layouts/default/oro_product_frontend_product_view/cache_product_view.yml
    1layout:
    2  actions:
    3    - '@setOption':
    4        id: product_view_container
    5        optionName: cache
    6        optionValue:
    7          tags:
    8            - '="product_" ~data["product"].getId()'
    
  2. Create an event listener that will call the invalidateTags() method on post update event:

    src/AcmeDemoBundle/EventListener/ProductUpdateListener.php
     1<?php
     2
     3namespace AcmeDemoBundle\EventListener;
     4
     5use Doctrine\ORM\Event\LifecycleEventArgs;
     6use Oro\Bundle\ProductBundle\Entity\Product;
     7use Symfony\Component\Cache\Adapter\TagAwareAdapterInterface;
     8use Symfony\Contracts\Cache\TagAwareCacheInterface;
     9
    10class ProductUpdateListener
    11{
    12    /** @var TagAwareAdapterInterface */
    13    private $cache;
    14
    15    public function __construct(TagAwareAdapterInterface $cache)
    16    {
    17        $this->cache = $cache;
    18    }
    19
    20    public function postUpdate(LifecycleEventArgs $args)
    21    {
    22        $entity = $args->getEntity();
    23        if ($entity instanceof Product) {
    24            $this->cache->invalidateTags(['product_'.$entity->getId()]);
    25        }
    26    }
    27}
    
  3. Register the listener in a service container:

    src/AcmeDemoBundle/Resources/config/services.yml
    1services:
    2  Oro\Bundle\LayoutCacheBundle\EventListener\ProductUpdateListener:
    3    arguments:
    4      - '@oro.layout_cache.tag_aware_cache_adapter'
    5    tags:
    6      - { name: doctrine.event_listener, event: postUpdate }
    

Configure the Cache Storage

You can use filesystem or Redis as a cache storage. By default, render cache uses filesystem cache storage.

To enable Redis support, append the following config to the config/config.yml file.

config/config.yml
1framework:
2  cache:
3    pools:
4      cache.oro_layout.render:
5        adapter: cache.adapter.doctrine
6        provider: oro.layout_cache.cache_provider

Pay attention, that Redis configuration is not compatible with the filesystem cache storage. To enable filesystem storage back, remove the above mentioned configuration.

When using Redis, it is recommended to use a separate server for the render cache. To configure it:

  1. Define a new client in the snc_redis configuration section and specify the connection DSN, e.g.,:

    config/config.yml
    1snc_redis:
    2    clients:
    3        render_cache:
    4            type: predis
    5            dsn: redis://localhost/5
    
  2. Override the oro.layout_cache.cache_provider service to use a new Redis client:

    src/AcmeDemoBundle/Resources/config/services.yml
    1services:
    2  oro.layout_cache.cache_provider:
    3    class: Doctrine\Common\Cache\PredisCache
    4    arguments:
    5      - '@snc_redis.render_cache'
    

Clear the Render Cache

To clear the render cache, run the command below:

php bin/console cache:pool:clear cache.oro_layout.render

Note

It is recommended to clear the render cache after any cache-related changes.