Jump to content
mav_medved

A custom cache key before rendering the page, using a built-in template cache engine

Recommended Posts

Hi all,

Keen on processwire. Thanks a lot for this thing!

But here is my issue:

I have a lot of pages that need to be cached. But the content on this pages depends on what user has in his session's variable (not a logged-in user, just a guest but with a different session's variable value).

So I need to add this session variable as a cache key before page will have been rendered and created the cache file.

How to do so?

I tried to find the solution, but there is no Hooks in wire/core/CacheFile.php

So, my thoughts:

1. add the Hook for method "buildFilename" in wire/core/CacheFile.php to have the possibility to change filename for cache file (or at least to add custom cache key for filename)

or

2. somehow do it using addHookBefore('Page::render'

For example: let's assume we have a special param like $options['custom_cache_key'] and we can change it inside Hook method (by the way how to do that?)

Share this post


Link to post
Share on other sites

hi mav_medved, welcome to the forum! :)

sounds like markupcache is the right thing for you:

https://processwire.com/talk/topic/7-new-markupcache-module/

http://modules.processwire.com/modules/markup-cache/

you could just create a cache-file bound to your session variable

$cache = $modules->get("MarkupCache");
if(!$data = $cache->get($your_session_var)) {
      $data = [...] // your code
      $cache->save($data);
}
echo $data;

don't know if or what procache has to offer in this case...

hope that helps :)

  • Like 1

Share this post


Link to post
Share on other sites
BernhardB, thanks for response!

A very nice module, I've found it very useful! Thanks for advice!

But I needed to make cache not for a part of the template, but whole template. (have some specific :))

So I came up with the solution, using this module:

(maybe someone will find it useful too)



<?
$cache = $modules->get("MarkupCache");
$cache_key = 'page_'.$page->id.'_myvar_'.$my_session_var;

if (!isset($options['render_for_cache'])){
$page->template->prependFile = '';
if (!$output = $cache->get($cache_key)){
$output = $page->render(array('render_for_cache' => 1, 'prependFile' => '', 'appendFile' => ''));
$cache->save($output);
}
echo $output;
}
else{
?>

<!-- here is my plain html/php markup -->

<?
}
?>

So now I can make a cache for any template with any cache_key.

I'm sure it's possible to make a Hook using "before render" for certain templates, so that can make cache and keep the template file clean. (or maybe not :D)

Anyway don't want to do it, ask me if someone need it ;)

  • Like 2

Share this post


Link to post
Share on other sites

nobody said it can't be used for the whole template ;)

hmm... nice. you could also handle everything in your template and outsource your markup to a different file:

yourtemplatefile.php

<?php
$config->session->myvar = 'test1'; // set session variable manually for testing

$cache = $modules->get("MarkupCache");
$cache_key = 'page_'.$page->id.'_myvar_'.$config->session->myvar;

if (!$output = $cache->get($cache_key)){
    $output = wireRenderFile('_markup.php');
    $cache->save($output);
}
echo $output;

_markup.php

<html>

[...]

<?= $page->title ?><br>
<br>
<?= $config->session->myvar ?>

[...]

</html>

so all your templates that are using "yourtemplatefile.php" will have cached output based on your session key. don't know how this compares to templatecache regarding performance but would be interesting to know :)

  • Like 1

Share this post


Link to post
Share on other sites

Very interesting Adam :) do you have any benchmarks compared to the standard template cache or to no cache?

Share this post


Link to post
Share on other sites

No 'real benchmarks' as in repeated tests on X different scenarios. Original usecase (and one measured) is a template listing shop items — ~40 products — where only difference in the rendered HTML is an input value - which is either default '0' or anything else picked up from $post or session.

It's a rather slow server, but load time for that page dropped from ~2.5s to ~450ms, which is the same as template caching (roughly), but usable on every page load, not only the first one.

I use MarkupCache (which in turn uses the same caching mechanism as the template-level caching), so there is maybe three or four function calls 'overhead' versus the template-level caching — which is nothing (I might be wrong, haven't been digging in that code lately).

---

There is a number of improvements I would like to make, but was working on a different projects lately.

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By MoritzLost
      Cacheable Placeholders
      This module allows you to have pieces of dynamic content inside cached output. This aims to solve the common problem of having a mostly cacheable site, but with pieces of dynamic output here and there.  Consider this simple example, where you want to output a custom greeting to the current user:
      <h1>Good morning, <?= ucfirst($user->name) ?></h1> This snippet means you can't use the template cache (at least for logged-in users), because each user has a different name. Even if 99% of your output is static, you can only cache the pieces that you know won't include this personal greeting. A more common example would be CSRF tokens for HTML forms - those need to be unique by definition, so you can't cache the form wholesale.
      This module solves this problem by introducing cacheable placeholders - small placeholder tokens that get replaced during every request. The replacement is done inside a Page::render hook so it runs during every request, even if the response is served from the template cache. So you can use something like this:
      <h1>Good morning, {{{greeting}}}</h1> Replacement tokens are defined with a callback function that produces the appropriate output and added to the module through a simple hook:
      // site/ready.php wire()->addHookAfter('CachePlaceholders::getTokens', function (HookEvent $e) { $tokens = $e->return; $tokens['greeting'] = [ 'callback' => function (array $tokenData) { return ucfirst(wire('user')->name); } ]; $e->return = $tokens; }); Tokens can also include parameters that are parsed and passed to the callback function. There are more fully annotated examples and step-by-step instructions in the README on Github!
      Features
      A simple and fast token parser that calls the appropriate callback and runs automatically. Tokens may include multiple named or positional parameters, as well as multi-value parameters. A manual mode that allows you to replace tokens in custom pieces of cached content (useful if you're using the $cache API). Some built-in tokens for common use-cases: CSRF-Tokens, replacing values from superglobals and producing random hexadecimal strings. The token format is completely customizable, all delimiters can be changed to avoid collisions with existing tag parsers or template languages. Links
      Github Repository & documentation Module directory If you are interested in learning more, the README is very extensive, with more usage examples, code samples and usage instructions!
    • By MoritzLost
      Process Cache Control
      This module provides a simple solution to clearing all your cache layers at once, and an extensible interface to perform various cache-related actions.
      The simple motivation behind this module was that I was tired of manually clearing caches in several places after deploying a change on a live site. The basic purpose of this module is a simple Clear all caches link in the Setup menu which clears out all caches, no matter where they hide. You can customize what exactly the module does through it's configuration menu:
      Expire or delete all cache entries in the database, or selectively clear caches by namespace ($cache API) Clear the the template render cache. Clear out specific folders inside your site's cache directory (/site/assets/cache) Clear the ProCache page render cache (if your site is using ProCache) Refresh version strings for static assets to bust client-side browser caches (this requires some setup, see the full documentation for details). This is the basic function of the module. However, you can also add different cache management action through the API and execute them through the module's interface. For this advanced usage, the module provides:
      An interface to see all available cache actions and execute them. A system log and logging output on the module page to see verify what the module is doing. A CacheControlTools class with utility functions to clear out different caches. An API to add cache actions, execute them programmatically and even modify the default action. Permission management, allowing you granular control over which user roles can execute which actions. The complete documentation can be found in the module's README.
      Plans for improvements
      If there is some interest in this, I plan to expand this to a more general cache management solution. I particular, I would like to add additional cache actions. Some ideas that came to mind:
      Warming up the template render cache for publicly accessible pages. Removing all active user sessions. Let me know if you have more suggestions!
      Links
      https://github.com/MoritzLost/ProcessCacheControl ProcessCacheControl in the Module directory CHANGELOG in the repository Screenshots


    • By verdeandrea
      Hello,
      I am using ProCache v3.1.8 on ProcessWire 3.0.96.
      Everything worked fine in the past, but today I noticed that the css file serverd by procache gives a 410 error. 
      The file is there, I checked.
      I deleted the cached files, I deleted the css file, I looked into the .htaccess file looking for some clues about this problem but nothing worked.
      The only way i can see my website correctly again is disabling ProCache. 
      Has anyone any clue on what could be the cause of the problem or on what should I do to fix it?
      Thanks!
    • By abdulqayyum
      Hy Processwire community,
      There are some problem in fileCompiler cache.
      when i change under the directory \site\templates\ it must change under the directory /site/assets/cache/FileCompiler/site/templates/
      but it does not update and functionality working with /site/assets/cache/FileCompiler/site/templates/ directory.
       
      In this case please suggest me how i clear fileCompiler cache?
      what i have to clear it manually?
      Thanks AbdulQayyum.
    • By modifiedcontent
      I had upgraded my Apache configuration to include PHP7.2 and PHP7.3 for a Laravel-based script on the same server. Somehow it/I messed up a previously fine Processwire site, in a very confusing way.
      The site still looks fine, but editing template files has no effect whatsoever. It is stuck on some kind of cached version. I have already disabled PHP7's OPcache, cleared browser caches, etc, with no effect.
      The pages now apparently come from PW's assets/cache/FileCompiler folder, even though I never enabled template caching for this site.
      I have tried adding "namespace ProcessWire;" to the top of the homepage template file, but then I get this fatal error:
      My functions.php file pulls data in from another Processwire installation on the same VPS with the following line:
      $othersitedata = new ProcessWire('/home/myaccount/public_html/myothersite/site/', 'https://myothersite.com/'); That apparently still works fine; the site still displays data from the other installation, but via the "cached" template that I am now unable to change.
       
      I don't know where to start with this mess. Does any of this sound familiar to anyone? Any pointers in the right direction would be much appreciated. 
       
      Edit:
      Adding "$config->templateCompile = false;" to config.php results in the same fatal error as above. 
×
×
  • Create New...