Looking by the code used, something like this would be even cleaner in the controller (given that you use PHP 7 or newer):
$this->set('debug', Configure::read('debug') ?? false);
That will automatically check if Configure::read('debug')
doesnât return null
(which means the key isnât set in the config) and if it does default to false
(otherwise, itâll just use the value set in the config obviously).
Getting back on topic, Using Configure::read
inside the template is kinda against the purpose of MVC, however, since Iâm not a purist, I generally ask myself: âcan a front-end developer with very little knowledge on back-end PHP quickly understand this?â and âdoes this not increase complexity of the template?â.
If the answer is yes: I allow myself to use it in the template.
If the answer is no: I keep it inside the controller.
For example take this piece of code.
I could write it like this in my template (yes, I could use a ternary operator here too but thatâs not the point):
<div class="container">
<?php if(Configure::read('debug') === true): ?>
<!-- Bypassed blogpost render cache -->
<?= $this->shortcode->doShortcode($article->body, ['cache' => null]); ?>
<?php else: ?>
<!-- Use blogpost render cache -->
<?= $this->shortcode->doShortcode($article->body, ['cache' => 'blog-rendered-' . $article->hash]);
<?php endif; ?>
</div>
Yes, itâd be reasonably understandable, but I could also make it easier on my âfront-end developersâ by doing this in my controller:
$this->set('shortcodeCache', Configure::read('debug') ? null : 'blog-rendered-' . $article->hash);
And then just having the front-end developer only write this:
<div class="container">
<?= $this->shortcode->doShortcode($article->body, ['cache' => $shortcodeCache]);
</div>
As you can see, I have now achieved the same effect, without making my template bloated and more complex.
Additionally, if the logic to decide whether to use the cache changes (eg. disabling it for certain users/roles, disabling it based on whether the post is popular enough - to save some memory in my cache -, changing the way we get the cache name etc.), the template wonât get bloated for those things and I donât need to bother my front-end developers with it at all (they donât care about it, they just know they need to pass $shortcodeCache
down and thatâs it).
However, something like this:
<?php if(Configure::read('debug') === true): ?>
<div class="container">
You are using this app in debug mode!
</div>
<?php endif; ?>
Barely increases the complexity because it is barely any different from this, and as such, Iâll allow it:
<?php if($debug === true): ?>
<div class="container">
You are using this app in debug mode!
</div>
<?php endif; ?>