2

I've been struggling with Magento\Catalog\Block\Product\ListProduct::initializeProductCollection() from a few days.

I need to filter category product collection based on user's location. So forexample I've to show 2 types of listings: one for location-based(when user's location is set) and other for non-location based (when user's location is not set). The location based listing is basically a filtered set of the product collection. Simply, I don't want to show certain type of product to customer if his location is set.

I've written my custom code to filter product collection but the problem happens when I change the location, it still shows me old collection. I know the full page caching is making issues. I tried making the lifetime of cache ListProduct block as null but still I'm able to see the old collection until I clear the cache.

Question:

Is there a way I can define custom caching process for caching the category page?

1 Answer 1

0

The full page cache identifies a cached page based on an identifier build from external information like the request URI including parameters, some cookie information etc.

If you are using full page caching the easiest way to achieve location based caching would be to pass the location (or whatever related information to identify the location) as url parameter. In this case the full page caching would use this parameter out-of-the-box for the cache identifier.

If that's not possible - for whatever reason - you can add that data to the X-Magento-Vary cookie which is also part of the full page cache identifier. For achieving this you have to set the value of your variable into \Magento\Framework\App\Http\Context. The X-Magento-Vary cookie is build automatically with all values set in a request. For the sake of example here a code sample for achieving this:

$objectManager->create('Magento\CatalogRule\Model\ResourceModel\RuleFactory')->create();
$httpContext = $objectManager->get('\Magento\Framework\App\Http\Context'); 
$httpContext->setValue('customer_location', <set your value here>,'');

The downside of that approach is that you have to set the information with every request, so you need to choose an appropriate plugin / event to hook in, which is always processed even in full page caching mode (an example of this usage is the plugin Magento\Customer\Model\App\Action\ContextPlugin). And you will have a multiple of cache entries since every page would be cached for every location set by that cookie. Therefore I wouldn't recommend that approch.

If you use all other caching types but full page caching I would recommend to make your location value part of the cache key, for example with a plugin after getCacheKeyInfo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.