Chapters Close

How to use cache-clean.js watcher utility in Magento 2?

Jun 13th, 2019 3 min to read

In this article you will be learning about how can use cache-clean.js watcher utility in Magento 2.

The file watcher automatically cleans affected cache types in the Magento 2 cache during development. For example, if you make a change to a template, it only cleans the block_html and full_page caches, not the config or layout caches.

Whole cache flush decrease developer’s performance, so we can use mage2tv/magento-cache-clean

Before starting the installation, we need Node.js version 8.x or above as dependency.

Install For Specific Project

Step 1

Install the node.js, using below command sudo apt-get install nodejs

Confirm node js installation using command node -v

Step 2

Now install mage2tv/magento-cache-clean  for specific project, go at root directory of your project and run below command
composer require --dev mage2tv/magento-cache-clean

Step 3

Confirm cache-clean installation using command vendor/bin/cache-clean.js

If you get the error Error NOSPC on Linux, run the command:

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

After successfully installation you get output Like:

Release 0.0.42 sponsored by https://www.mage2.tv

Flushing all caches

Usage

In your Magento directory, run vendor/bin/cache-clean.js --watch or -w
Now watch is start, Press Ctrl+C to exit the watcher process.
The file watcher automatically cleans affected cache types, watch will show notification in the terminal about the specific cache clean and recompiles the changes simultaneously.

Hotkeys

When the watcher is running, segments of the cache can be cleaned with individual key press:

KeyCache Segment(s)
cconfig
bblock_html
llayout
ffull_page
a(a for all)
v(V for view) block_html, layout, full_page
ttranslate

There also are hotkeys to clean the static assets in the Adminhtml or the Frontend area or clean the Generated code directory

KeyWork
F Clean Frontend static assets
A Clean Adminhtml static content
G Clean Generated code

Install Globally

Step 1

Now install mage2tv/magento-cache-clean globally run below command
composer global require --dev mage2tv/magento-cache-clean

Step 2

verify where installed it in your pc or system in my case at => home/.config/composer/vendor/bin/cache-clean.js

Step 3

set system path using this command
export PATH="$PATH:$HOME/.config/composer/vendor/bin"

Now the installation process is completed, the next step is to run the cache command.

Step 4

From any project’s root directory you can access using  cache-clean.js

From out-off magento root directory can access using full directory path cache-clean.js -d ./magento230
Here -d or –directory for Magento Base Directory, magento230 is project name

Note: For globally installation can start watch using  cache-clean.js -w or cache-clean.js -d ./magentodirectory -w, For specific installation using vendor/bin/cache-clean.js -w

Reference From:

Git Hub: https://github.com/mage2tv/magento-cache-clean/blob/master/readme.md
Mage2tv:https://www.mage2.tv/content/fundamentals/magento-cli-tool/the-magento-cache-clean-js-file-watcher-utility/

How to Add block to cache in Magento 2

Feb 26th, 2019 2 min to read

As we all know that are many cases in Magento 2 where product listing is too big that affects page load time. Now you can decrease the page load time by adding that specific block to the cache. Below are the different ways to achieve your goal:

Add a block to cache from layout xml:

Add below _construct() in your respected block file and specify cache_lifetime and a unique cache_tags cache identifier.

{{block name="explore-color-section" class="Companyname\Packagename\Block\Product\CustomProductCollection" product_id="51,52,53,54,55,56,57,58,59,60,40, 41, 42, 43, 44, 45, 46, 47, 70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90 ,91,92,93,94,95,96,97,98,99,100,101,102,103" cacheable="true" cache_lifetime="86400" template="Magento_Theme::html/explore_color_code.phtml"}}

Add a block to cache from block file:

Add the _construct () given below in your respected block file and specify cache_lifetime and a unique cache_tags cache identifier.

/**
     * {@inheritdoc}
     */
    protected function _construct()
    {
        parent::_construct();
        $this->addData([
            'cache_lifetime' => 86400,
            'cache_tags' => ["explore_your_colors_ilnp"]]);
    }

Note: Here its _construct not __construct

Add a block having pagination to cache(Ex. Product listing with pagination):

Add the  _construct() given below in your respected block file and specify cache_lifetime and a unique cache_tags cache identifier.

 protected function _construct()
    {
        parent::_construct();
        $this->addData([
                'cache_lifetime' => 86400,
                'cache_tags' => [\Magento\Store\Model\Store::CACHE_TAG, \Magento\Cms\Model\Block::CACHE_TAG],
                'cache_key'  => "explore_your_colors_ilnp_".$this->request->getPost('page_number')
            ]
        );
    }

Lastly, run the command given below to make changes effective:

php bin/magento cache:clean
php bin/magento cache:flush

In this article, you will be learning how to get customer session data when a cache is enabled in Magento 2.

Before you read this article, please refer our blog about “Magento 2: How to check customer is logged in or not when a cache is enabled”.

We can’t get any data from customer session when a cache is enabled Because as soon as layout generation started, customer session will be cleared by \Magento\PageCache\Model\Layout\DepersonalizePlugin::afterGenerateXml on all cacheable pages. So we can’t get any customer session data from \Magento\Customer\Model\Session.

As per our previous blog, using httpContext we can get a customer is logged in or not. But what about if you want to get customer id, name, email and other customer attributes.

By default, In httpContext only customer_group and customer_not_logged_in are defined. So Customer id, Name, Email and other customer attributes are not defined in httpContext.

So we will create a plugin to set customer session data in httpContext.

Please follow the below steps
1.Define plugin a di.xml file
2. Create a plugin 
3. Use httpContext data in block

1.Define plugin in di.xml file

Create a di.xml file in app/code/Aureatelabs/ModuleName/etc/frontend directory.

<?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\Framework\App\Action\AbstractAction">
    	<plugin name="customer-session-data-to-context" type="Aureatelabs\ModuleName\Plugin\CustomerSessionContext" sortOrder="15"/>
	</type>
</config>

2. Create a plugin

Create CustomerSessionContext.php file in app/code/Aureatelabs/ModuleName/Plugin directory.

<?php
namespace Aureatelabs\ModuleName\Plugin;

class CustomerSessionContext
{
	/**
 	* @var \Magento\Customer\Model\Session
 	*/
	protected $customerSession;

	/**
 	* @var \Magento\Framework\App\Http\Context
 	*/
	protected $httpContext;

	/**
 	* @param \Magento\Customer\Model\Session $customerSession
 	* @param \Magento\Framework\App\Http\Context $httpContext
 	*/
	public function __construct(
    	\Magento\Customer\Model\Session $customerSession,
    	\Magento\Framework\App\Http\Context $httpContext
	) {
    	$this->customerSession = $customerSession;
    	$this->httpContext = $httpContext;
	}

	/**
 	* @param \Magento\Framework\App\ActionInterface $subject
 	* @param callable $proceed
 	* @param \Magento\Framework\App\RequestInterface $request
 	* @return mixed
 	*/
	public function aroundDispatch(
    	\Magento\Framework\App\ActionInterface $subject,
    	\Closure $proceed,
    	\Magento\Framework\App\RequestInterface $request
	) {
    	$this->httpContext->setValue(
        	'customer_id',
        	$this->customerSession->getCustomerId(),
        	false
    	);

    	$this->httpContext->setValue(
        	'customer_name',
        	$this->customerSession->getCustomer()->getName(),
        	false
    	);

    	$this->httpContext->setValue(
        	'customer_email',
        	$this->customerSession->getCustomer()->getEmail(),
        	false
    	);

    	return $proceed($request);
	}
}

We have to get data like customer_id, customer_name and customer_email from customer session and set in in httpContext using the plugin.

You can also set other customer data same as above and can be used in our block.

3. Use httpContext data in Block

Initialize \Magento\Framework\App\Http\Context in your custom block file.

<?php

namespace Aureatelabs\ModuleName\Block;

class CustomBlock extends \Magento\Framework\View\Element\Template
{
	protected $httpContext;

	public function __construct(
    	\Magento\Framework\View\Element\Template\Context $context,
    	\Magento\Framework\App\Http\Context $httpContext,
    	array $data = []
	) {
    	$this->httpContext = $httpContext;
    	parent::__construct($context, $data);
	}

	public function getCustomerIsLoggedIn()
	{
    	return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
	}

	public function getCustomerId()
	{
    	return $this->httpContext->getValue('customer_id');
	}

	public function getCustomerName()
	{
    	return $this->httpContext->getValue('customer_name');
	}

	public function getCustomerEmail()
	{
    	return $this->httpContext->getValue('customer_email');
	}

}

Now you can get customer id, name and email from the block and can be used in the frontend. It will be displayed even a page cache is enabled.

I hope this will help you in implementing your own logic.

FAQs

How cache is working in Magento 2?


Cache is working in Magento 2 by storing data in quickly accessible memory so the site can perform faster. A reverse PHP proxy is available in Magento 2 which allows caching the full page. This decreases the load time of the site. Other types of caches such as the block HTML output and layout cache also improve site performance.

How do I enable full page cache in Magento 2?


To enable full-page cache in Magento 2, follow the below steps.
1. Login to the admin account
2. Click on Stores>Settings>Configuration>System
3. In the “Advanced” menu, scroll to the full page cache section.
4. Select “Built-In Application” in the caching application.
5. In the TTL for Public Content, set a desired time. After this time limit, the page data gets updated. 
6. Click the “Save Config” button to save the settings.

How to manage cache in magento 2?


To manage cache in Magento 2, you can use the admin panel. In the “Systems” menu, you can find “Cache Management.” Clicking on it will allow you to enable, disable, or refresh cache. Select one of the options and click submit to run the command. You can also clear existing cache data by clicking on the “Flush Magento Cache” option at the top.

How to clear full page cache magento 2?


To clear full page cache in Magento 2, follow these steps. 
1. Login to the admin dashboard.
2. Click on the “Systems” menu and then “Cache Management.”
3. Tick all the boxes under “Cache Types.”
4. Click on the “Flush Magento cache” button at the top of the panel.

In this article, you will be learning how to check customer is logged in or not when a cache is enabled in Magento 2.

We can easily check this when a cache is disabled or in the controller, you can get this from customer session.

class Index extends \Magento\Framework\App\Action\Action
{
	/**
 	* @var  \Magento\Customer\Model\Session
 	*/
	public $customerSession;

	/**
 	* @param \Magento\Framework\App\Action\Context $context
 	* @param \Magento\Customer\Model\Session $customerSession
 	*/
	public function __construct(
    	\Magento\Framework\App\Action\Context $context,
    	\Magento\Customer\Model\Session $customerSession
	) {
    	$this->customerSession = $customerSession;
    	parent::__construct($context);
	}
	public function execute()
	{
    	if($this->customerSession->isLoggedIn()) {
        	// Customer is logged in

    	} else {
        	// Customer is not logged in
    	}

	}
}

Above code will work in the controller. This code will not work in block or helper when a cache is enabled.

Because When a cache is enabled, as soon as layout generation started, customer session will be cleared by \Magento\PageCache\Model\Layout\DepersonalizePlugin::afterGenerateXml on all cacheable pages. So we can’t get any customer session data from \Magento\Customer\Model\Session.

So, how to check customer is logged in or not when the page cache is enabled?

There is two way to achieving our goal
1. Using cacheable false in layout
2. Using httpContext

1. Using cacheable false in layout

<block class="Aureatelabs\ModuleName\Block\CustomBlock" name="aureatelabs_custom_block" template="Aureatelabs_ModuleName::custom.phtml" cacheable="false"/>

Using cacheable false for your custom block in layout, you will get all customer session data in your custom block now.

But there is one drawback of this method. When you use cacheable=false XML attribute in your layout entire page will disable Full Page Caching for the whole page, making the pages sourcing from that layout file extremely slow.

The most prevalent and harmful misinformation on full page caching is around the usage of the cacheable=false XML attribute. Including this attribute on a block will make any page that uses that block uncacheable. Unfortunately, there’s a lot of misinformation floating around and many cases where developers are using this to “solve” their problem, but actually breaking FPC.If you don’t want to disable your full page caching, there is another way using httpContext.

2. Using httpContext

Initialize \Magento\Framework\App\Http\Context in your Block or Helper. I have injected in my custom block.

protected $httpContext;

public function __construct(
	\Magento\Framework\View\Element\Template\Context $context,
	\Magento\Framework\App\Http\Context $httpContext,
	array $data = []
) {
	$this->httpContext = $httpContext;
	parent::__construct($context, $data);
}

public function getCustomerIsLoggedIn()
{
	return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}

This method will return a boolean value. If the customer is logged in it will return true and when the customer is not logged in it will return false.

To get customer session data like customer id, name and email when a cache is enabled, please refer our next blog “How to get customer session data when a cache is enabled”.

Grow your online business like 2,874 subscribers

    * This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
    envelope

    Thank You!

    We are reviewing your submission, and will be in touch shortly.