Advertisement

Facebook

Preventing PHTML Templates from FPC/Varnish Cache in Magento 2.4.X : A Complete Guide

Preventing PHTML Templates from FPC/Varnish Cache in Magento 2.4.X : A Complete Guide


Caching is essential in Magento 2.4.X to boost performance and page load speeds. However, there are cases where specific templates, especially those containing customer-specific data, need to be excluded from Full Page Cache (FPC) and Varnish Cache to ensure the data remains dynamic. In this guide, we'll discuss how to achieve this efficiently.

By default, Magento 2 uses Full Page Cache (FPC) and Varnish to cache entire pages, which improves performance. However, this can be an issue for certain templates. If your PHTML template includes PHP logic that changes based on the user or location, it might not be suitable for caching. Setting cacheable="false" in your layout XML file would turn off caching for the entire page, which isn't ideal.

Step-by-Step Solution: Using Magento’s Private Content Mechanism

Magento 2 allows you to handle user-specific data using private content sections. This approach loads specific content per user dynamically without caching the entire block.

Example Implementation:

Step-1: Create the registration.php file at app/code/VendorName/ModuleName and add the following code:


<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'VendorName_ModuleName',
    __DIR__
);

Step-2: Create the module.xml file at app/code/VendorName/ModuleName/etc and add the following code:


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="VendorName_ModuleName" setup_version="1.0.0">
    </module>
</config>

Step-3: Create the di.xml file at app/code/VendorName/ModuleName/etc/frontend and add the following code:


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Customer\CustomerData\SectionPoolInterface">
        <arguments>
            <argument name="sectionSourceMap" xsi:type="array">
                <item name="custom_section" xsi:type="string">VendorName\ModuleName\CustomerData\CustomSection</item>
            </argument>
        </arguments>
    </type>
</config>

Step-4: Create the CustomSection.php file at app/code/VendorName/ModuleName/CustomerData and add the following code:



namespace VendorName\ModuleName\CustomerData;

use Magento\Customer\CustomerData\SectionSourceInterface;

class CustomSection implements SectionSourceInterface
{
    protected $resultPageFactory;

    public function __construct(
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
    }

    public function getSectionData()
    {
        $resultPage = $this->resultPageFactory->create();
        $block = $resultPage->getLayout()
                ->createBlock(\Magento\Framework\View\Element\Template::class)
                ->setTemplate("VendorName_ModuleName::custom.phtml")
                ->toHtml();
        return [
            'customdata' => $block,
        ];
    }
}
  

Step-5: Create the CustomSection.php file at app/code/VendorName/ModuleName/CustomerData and add the following code:


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="*">
        <section name="custom_section" />
    </action>
</config>

Step-6: Create the default.xml file at app/code/VendorName/ModuleName/view/frontend/layout and add the following code:

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="custom.file.cacheable" template="VendorName_ModuleName::custom_cacheble.phtml" />
        </referenceContainer>
    </body>
</page>
	

Step-7: Create the custom_cacheble.phtml file at app/code/VendorName/ModuleName/view/frontend/templates and add the following code:

<div class="custom-section-show" data-bind="scope: 'section'">
    <div data-bind="html: customsection().customdata"></div>
</div>
<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "section": {
                        "component": "VendorName_ModuleName/js/section"
                    }
                }
            }
        }
    }
</script>
  

Step-8: Create the custom.phtml file at app/code/VendorName/ModuleName/view/frontend/templates and add the following code:

<?php
// $locale = Locale::acceptFromHttp($_SERVER['HTTP_CF_IPCOUNTRY']);
$locale = 'be';
?>
<?php if ($locale == "be"):?>

<h1>HTML CODE BE</h1>

<?php elseif ($locale == "uk"):?>

<h1>HTML CODE UK</h1>


<?php endif;?>
  

Step-9: Create the custom_cacheble.phtml file at app/code/VendorName/ModuleName/view/frontend/templates and add the following code:


define([
    'uiComponent',
    'Magento_Customer/js/customer-data'
], function (Component, customerData) {
    'use strict';

    return Component.extend({
        initialize: function () {
            this._super();
            var sections = ['custom_section'];
            customerData.invalidate(sections);
            customerData.reload(sections, true);
            this.customsection = customerData.get('custom_section');
        }
    });
});

Output:

Preventing PHTML Templates from FPC/Varnish Cache in Magento 2.4.X : A Complete Guide

Effectively managing caching in Magento 2.4.X is essential for balancing performance and the need for dynamic content. Caching enhances site speed and user experience but can also lead to issues when dealing with templates requiring real-time data updates.

To maintain dynamic behavior in your PHTML templates while ensuring that most of the page remains cached, consider using features such as custom data sections.

Custom Data Sections allow you to define specific parts of your page that can be updated independently from the rest of the content. This means you can keep the bulk of your page cached for optimal performance while ensuring that critical dynamic areas are always current. By implementing custom data sections, you can provide real-time updates for elements like shopping cart contents, customer-specific promotions, or user account information without affecting the cached state of the entire page. This approach not only enhances the user experience by delivering timely information but also significantly improves loading speeds for the static parts of the page.

I hope this information helps you effectively manage caching in your Magento 2.4.X store. If you have any questions or uncertainties regarding this topic, please feel free to leave your doubts in the comments section below. I’m here to assist you!

Post a Comment

0 Comments

Buy Me A Coffee