Let say I have a webshop open from 9am to 11am (data coming from config). When the shop is closed, I would like to display a message (shop closed) and when the shop is open, my commerce product should be available. (only for 'lunch' bundle)
I have tried to update the following code: https://cornel.co/article/drupal8/page-cache-cookies-or-anything-available-http-request
Here is my try (edited with a comment from 4k4:
protected function getCacheId(Request $request)
{
if (! isset($this->cid)) {
$cid_parts = [
$request->getSchemeAndHttpHost() . $request->getRequestUri(),
$request->getRequestFormat(NULL)
];
// Only cache by State of Store for some path
if (strpos($request->getPathInfo(), '/lunches/') != false) {
$store_state = get_store_state();
$cid_parts[] = $store_state['context']; //return a string like 'open' or 'close:9:30:11:00' if closed (like before 9:30 am or after 11:00am)
}
$this->cid = implode(':', $cid_parts);
}
return $this->cid;
}
As stated by 4k4, I must create a new context which will bubble up and will invalidate the Internal Cache page.
Here is the code of
class StateStoreCacheContext implements CacheContextInterface
stored in mymodule/src/CacheContext/StateStoreCacheContext.php
public function getContext()
{
$storeState=get_store_state();
return $storeState['context']; //return a string like 'open' or 'close:9:30:11:00' if closed (like before 9:30 am or after 11:00am)
}
And here is mys service declaration:
services:
cache_context.state_store_context:
class: Drupal\mymodule\CacheContext\StateStoreCacheContext
arguments: []
tags:
- { name: cache.context }
And here is the way I add my context to my page (in mythem_preprocess_node(&$vars)
)
$vars['#cache']['contexts'][] = 'state_store_context';
Unfortunately, my page cache is not invalidate for anonymous users (but it is ok for logged-in users)
get_context()
with exactly the same logic as ingetCacheId()
(see upper)=>looks weird 2-My idea is to keep the internal page cache module, I have read somewhere else that it doesn't deal with context. Thank you for the route not being present, I will update the code