Run plugin code on load


#1

In some past posts of mine, I have tried getting something to work.
This something is a little piece of code in a plugin that calls on a component in a core plugin.

However, this has gotten me into some issues:

  • Placing this code in the AppController:initialize results in this code not running at all unless something specific to the plugin is also loaded (eg. a controller in the plugin)
  • Placing this code in the bootstrap.php results in the app breaking when having an empty database (eg. after having to re-install a workstation)

My question is, where and how should I do this in a proper fashion?
This is the code I’m trying to run:

...

$this->loadComponent('Kikioboeru/Kikioboeru.Settings');

// Create new settings group
$this->Settings->registerGroup([
  'group'=>'smtp',
  'label'=>'Mailserver Settings'
]);

// Add items to the settings group
$this->Settings->registerOption([
  'type'=>'text',
  'name'=>'smtp_host',
  'value'=>$this->Settings->getOptionValue('smtp_host'), // Here, the issue arrises
  'group'=>'smtp',
  'label'=>'Host',
  'placeholder'=>'Your mailserver\'s address'
]);

...

UPDATE 1: While waiting for a proper solution on this issue, I have opted to place the code back in bootstrap.php and wrap it in an if(PHP_SAPI === 'fpm-fcgi'){ to check whether we are using the CLI (so it doesn’t break the cake CLI tool) or a browser.


#2

This is the correct place, but you need only run the code if the expected table is present. The simplest way is to wrap the troublesome call with a try {...] catch () {...}