It's probably a duplicate.
Anyhow, I am writing a J5 content plugin using onContentPrepare
event.
It turns out, that this plugin is called several times before the page is sent to the browser.
I want to execute a short code only during the first call and any subsequent plugin calls to check that flag.
For that reason, I need a flag to be reset before the first call and set on the first code execution. What is the best way to achieve this? Some kind of global variable?
Add a comment
|
1 Answer
Normally plugins in Joomla are instantiated only once per request. So using a class member variable is the cleanest solution:
use Joomla\CMS\Event\Content\ContentPrepareEvent;
use Joomla\CMS\Plugin\CMSPlugin;
final class MyPlugin extends CMSPlugin
{
private bool $flag = false;
public function onContentPrepare(ContentPrepareEvent $event)
{
// Check if flag has been set.
if (!$this->flag)
{
// Set the flag on first run.
$this->flag = true;
// Code that will be executed once.
}
// Code that will be executed every time.
}
}