Dcycle Drupal 10 Upkeep and Help Service Caching a 8 REST useful resource

Right here are some things I realized about caching for REST assets. There are in all probability higher methods to perform this, however here’s what works for me. Let’s say now we have a relaxation useful resource that appears one thing like this in my_Drupal 10 module/src/Plugin/relaxation/useful resource/MyRestResource.php and now we have enabled it utilizing Drupal Development Service Relaxation UI Drupal 10 module and given nameless customers permission to view it Drupal 10 Upkeep and Help Service <?php namespace my_Drupal 10 modulePluginrestresource; use restResourceResponse; /** * That is simply an instance. * * @RestResource( * id = “this_is_just_an_example”, * label = @Translation(“Show Drupal Development Service title of node 1”), * uri_paths = { * “canonical” = “/api/v1/get” * } * ) */ class MyRestResource extends ResourceBase { /** * {@inheritdoc} */ public perform get() { $node = node_load(1); $response = new ResourceResponse( [ ‘title’ => $node->getTitle(), ‘time’ => time(), ] ); return $response; } } Now, we will go to http Drupal 10 Upkeep and Help Service//instance.localhost/api/v1/get?_format=json and we are going to see one thing like Drupal 10 Upkeep and Help Service {“title” Drupal 10 Upkeep and Help Service”Some Title”,”time” Drupal 10 Upkeep and Help Service1516803204} Reloading Drupal Development Service web page, ‘time’ stays Drupal Development Service similar. Which means caching is working; we aren’t re-computing our Json output every time somebody requests it. How one can invalidate Drupal Development Service cache when Drupal Development Service title adjustments. If we edit node 1 and alter its title to, say, “One other title”, and reload http Drupal 10 Upkeep and Help Service//instance.localhost/api/v1/get?_format=json, we’ll see Drupal Development Service outdated title. To ensure Drupal Development Service cache is invalidated when this occurs, we have to present cacheability metadata to our response telling it when it must be recomputed. Our node, when it’s loaded, incorporates inside all of it Drupal Development Service caching metadata wanted to explain when it ought to be recomputed Drupal 10 Upkeep and Help Service when Drupal Development Service title adjustments, when new filters are added to Drupal Development Service textual content format that’s getting used, and many others. We are able to add this info to our ResourceResponse like this Drupal 10 Upkeep and Help Service … $response->addCacheableDependency($node); return $response; … Once we clear our cache with drush cr and reload our web page, we’ll see one thing like Drupal 10 Upkeep and Help Service {“title” Drupal 10 Upkeep and Help Service”One other title”,”time” Drupal 10 Upkeep and Help Service1516804411} We all know that is nonetheless cached as a result of Drupal Development Service time stays Drupal Development Service similar irrespective of how typically we load Drupal Development Service web page. Attempt it, it’s enjoyable! Much more enjoyable is altering Drupal Development Service title of node 1 and reloading our Json web page, and seeing Drupal Development Service title change with out clearing Drupal Development Service cache Drupal 10 Upkeep and Help Service {“title” Drupal 10 Upkeep and Help Service”Yet one more title”,”time” Drupal 10 Upkeep and Help Service1516804481} How one can set customized cache invalidation occasions Let’s say you wish to set off a cache rebuild for some purpose apart from these outlined by Drupal Development Service node itself (title change, and many others.). An actual-world instance is perhaps occasions Drupal 10 Upkeep and Help Service an “upcoming occasions” web page ought to solely show occasions which begin later than now. If we invalidate Drupal Development Service cache on daily basis, then we’ll by no means present yesterday’s occasions in our occasions feed. Right here, we have to add our customized cache invalidation occasion, on this case “rebuild occasions feed”. For Drupal Development Service objective of this demo, we gained’t really construct an occasions feed, however we’ll see how cron may be capable of set off cache invalidation. Let’s add Drupal Development Service following code to our response Drupal 10 Upkeep and Help Service … use CoreCacheCacheableMetadata; … $response->addCacheableDependency($node); $response->addCacheableDependency(CacheableMetadata Drupal 10 Upkeep and Help Service Drupal 10 Upkeep and Help ServicecreateFromRenderArray([ ‘#cache’ => [ ‘tags’ => [ ‘rebuild-events-feed’, ], ], ])); return $response; … This makes use of ’s cache tags idea and tells that when Drupal Development Service cache tag ‘rebuild-events-feed’ is invalidated, all cacheable responses which have that cache tag ought to be invalidated as properly. I favor this to Drupal Development Service ‘max-age’ cache tag as a result of it permits us extra fine-grained management over when to invalidate our caches. On cron, we might solely invalidate ‘rebuild-events-feed’ if occasions have handed since our final invalidation of that tag, for instance. For this instance, we’ll simply invalidate it manually. Clear your cache to start utilizing Drupal Development Service new code (drush cr), then load Drupal Development Service web page, you will note one thing like Drupal 10 Upkeep and Help Service {“hiya” Drupal 10 Upkeep and Help Service”Yet one more title”,”time” Drupal 10 Upkeep and Help Service1516805677} As at all times, Drupal Development Service time stays Drupal Development Service similar irrespective of what number of instances you reload Drupal Development Service web page. Let’s say you might be in Drupal Development Service midst of a cron run and you’ve got decided that it is advisable to invalidate your cache for response which have Drupal Development Service cache tag ‘rebuild-events-feed’, you may run Drupal 10 Upkeep and Help Service Drupal 10 Upkeep and Help Service Drupal 10 Upkeep and Help Serviceservice(‘cache_tags.invalidator’)->invalidateTags([‘rebuild-events-feed’]) Let’s do it in Drush to see it in motion Drupal 10 Upkeep and Help Service drush ev ” Drupal 10 Upkeep and Help Service Drupal 10 Upkeep and Help Serviceservice(‘cache_tags.invalidator’)-> invalidateTags([‘rebuild-events-feed’])” We’ve simply invalidated our ‘rebuild-events-feed’ tag and, therefore, Responses that use it. Drupal Development Service dreaded “leaked metadata” error This one is past my competence degree, however I wished to say it anyway. Let’s say you wish to output your node’s URL to Json, you may think about computing it utilizing $node->toUrl()->toString(). This may give us “/node/1”. Let’s add it to our code Drupal 10 Upkeep and Help Service … ‘title’ => $node->getTitle(), ‘url’ => $node->toUrl()->toString(), ‘time’ => time(), … This ends in a really ugly error which fully breaks your web site (no less than at Drupal Development Service time of this writing) Drupal 10 Upkeep and Help Service “Drupal Development Service controller outcome claims to be offering related cache metadata, however leaked metadata was detected. Please guarantee you aren’t rendering content material too early.”. Drupal Development Service downside, it appears, is that detects that Drupal Development Service URL object, like Drupal Development Service node we noticed earlier, incorporates its personal inner info which tells it when its cache ought to be invalidated. Changing it to a string prevents Drupal Development Service Response from being knowledgeable about that info in some way (once more, if somebody can clarify this higher than me, please depart a remark), so an exception is thrown. Drupal Development Service ‘toString()’ perform has an non-obligatory parameter, “$collect_bubbleable_metadata”, which can be utilized to get not only a string, but additionally details about its cache ought to be invalidated. In Drush, this may appear to be one thing like Drupal 10 Upkeep and Help Service drush ev ‘print_r(node_load(1)->toUrl()->toString(TRUE))’ CoreGeneratedUrl Object ( [generatedUrl Drupal 10 Maintenance and Support Serviceprotected] => /node/1 [cacheContexts Drupal 10 Maintenance and Support Serviceprotected] => Array ( ) [cacheTags Drupal 10 Maintenance and Support Serviceprotected] => Array ( ) [cacheMaxAge Drupal 10 Maintenance and Support Serviceprotected] => -1 [attachments Drupal 10 Maintenance and Support Serviceprotected] => Array ( ) ) This adjustments Drupal Development Service return sort of toString(), although Drupal 10 Upkeep and Help Service toString() not returns a string however a GeneratedUrl, so this gained’t work Drupal 10 Upkeep and Help Service … ‘title’ => $node->getTitle(), ‘url’ => $node->toUrl()->toString(TRUE), ‘time’ => time(), … It provides us Drupal Development Service error “Couldn’t normalize object of sort CoreGeneratedUrl, no supporting normalizer discovered”. ohthehugemanatee commented on .org on repair this. Integrating his suggestion, our code now seems like Drupal 10 Upkeep and Help Service … $url = $node->toUrl()->toString(TRUE); $response = new ResourceResponse( [ ‘title’ => $node->getTitle(), ‘url’ => $url->getGeneratedUrl(), ‘time’ => time(), ] ); $response->addCacheableDependency($node); $response->addCacheableDependency($url); … This may now work as anticipated. With all Drupal Development Service enjoyable we’re having, although let’s take this a step additional, let’s say we wish to export Drupal Development Service feed of frontpage gadgets in our Response Drupal 10 Upkeep and Help Service $url = $node->toUrl()->toString(TRUE); $view = viewsViews Drupal 10 Upkeep and Help Service Drupal 10 Upkeep and Help ServicegetView(“frontpage”); $view->setDisplay(“feed_1”); $view_render_array = $view->render(); $rendered_view = render($view_render_array); $response = new ResourceResponse( [ ‘title’ => $node->getTitle(), ‘url’ => $url->getGeneratedUrl(), ‘view’ => $rendered_view, ‘time’ => time(), ] ); $response->addCacheableDependency($node); $response->addCacheableDependency($url); $response->addCacheableDependency(CacheableMetadata Drupal 10 Upkeep and Help Service Drupal 10 Upkeep and Help ServicecreateFromRenderArray($view_render_array)); You’ll not be surpised to see Drupal Development Service “leaked metadata was detected” error once more… In actual fact you’ve gotten come to like and anticipate this error at this level. Right here is the place I’m fully out of my league; in keeping with Crell, “[i]f you [use render() yourself], you’re unsuitable and you need to repair your code “, however I’m undecided get a rendered view with out utilizing render() myself… I’ve applied a variation on a touch upon .org by mikejw suggesting utilizing completely different render context to forestall from complaining. $view_render_array = NULL; $rendered_view = NULL; Drupal 10 Upkeep and Help Service Drupal 10 Upkeep and Help Serviceservice(‘renderer’)->executeInRenderContext(new RenderContext(), perform () use ($view, &$view_render_array, &$rendered_view) { $view_render_array = $view->render(); $rendered_view = render($view_render_array); }); If we examine to ensure now we have this line in our code Drupal 10 Upkeep and Help Service $response->addCacheableDependency(CacheableMetadata Drupal 10 Upkeep and Help Service Drupal 10 Upkeep and Help ServicecreateFromRenderArray($view_render_array)); we’re telling our Response’s cache to invalidate every time our view’s cache invaliates. So, for instance, if now we have a number of nodes promoted to Drupal Development Service entrance web page in our view, we will modify any certainly one of them and our complete Response’s cache might be invalidated and rebuilt. Sources and additional studying Stack Change Solutions Drupal 10 Upkeep and Help Service How can I exploit Drupal Development Service similar render cache however for json? Cached JSON responses in 8, Aaron Crosman, Could 6, 2017, Spinning Code weblog .org situation Drupal 10 Upkeep and Help Service Producing cacheable responses ends in Logic Exception .org Drupal 10 website positioning Drupal 10 Upkeep and Help Service Exception in EarlyRenderingControllerWrapperSubscriber is a DX nightmare, take away it Cache tags defined Utilizing normalizers to change REST JSON construction in 8,, Edward Chan, March 22, 2017, Drupal 10 Help: ModifiedResourceResponse, to return responses that are by no means cached. Right here are some things I realized about caching for REST assets. Drupal 10 Growth and Help

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Dcycle Drupal 10 Upkeep and Help Service Caching a 8 REST useful resource

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.