Correct way to disable cache for logged in users?


#1

From several forum posts, it seems that the correct way to disable cache when a user is logged in is to place this in the config.php file:

if (!site()->user()):
	c::set('cache', true);
endif;

But I just found out a side effect from this when implementing the Kirby Algolia plugin.

For the Algolia plugin I need to specify the search index to be used. For the production site I have one index, and for the development version I have another index:

In config.php:

c::set('algolia.index', 'prod_index');

In config.localhost.php:

c::set('algolia.index', 'dev_index');

So by using this multi-environment setup I can overwrite the index setting on my local dev version.

This way of overwrite some config values works fine, until you have this code in your config.php:

if (!site()->user()):
	// Deactivate cache settings etc...
endif;

As soon as the line site()->user()runs in the config.php, any config setting in my config.localhost.php won’t overwrite anymore. So in my case, setting a different Algolia index on my local dev installation has no effect.

I have tried this with a fresh install of the Starterkit, and I can’t figure out what is wrong. But I guess that site()->user() does something in the background that prevents config settings to overwrite older settings.

So my question is two fold.

  1. Is this a bug that site()->user() prevents overwriting of config settings?
  2. Is there another way to disable cache if a user is logged in?

#2

Are all the config settings within this if statement? How about using different config files per domain:

config.php (general settings)
config.prodserver.php (settings for production)
config.localhost.php (settings for dev environment)


#3

No, in this if statement, I had only the code to disable the cache. But even if I remove the cache code, and just have an empty if statement, I can’t overwrite any config setting.


#4

You should try it out yourself with a fresh install of the Starterkit on a localhost:

config.php:

<?php

if (!site()->user()):
	// Deactivate cache settings etc...
endif;

c::set('algolia.index', 'prod_index');

config.localhost.php:

<?php

c::set('algolia.index', 'dev_index');

Then in a frontend template, try to echo the value of algolia.index:

<?= c::get('algolia.index'); ?>

You will always get prod_index as a result. But if you remove the site()->user() part, then you will get dev_index as output.


#5

You are right. If you change the order and place the if-statement at the end it seems to work. Don’t ask me what is causing this…


#6

Oh thanks, moving the if-statement at the end does indeed seems to work. perfect workaround.

Yeah this is a really strange behavior. Should I file an issue on one of the GitHub repos?


#7

Yes, please do, let’s have the devs look into this.


#8

I have created an issue now.

https://github.com/getkirby/toolkit/issues/253