I have written a plugin for CakePHP 3.4.*.
This plugin will check for Database configuration has been set or not, if not then It you move user through a GUI interface to setup database configuration just like wordpress.
The plugin is working perfectly, but it has to be loaded manually by visiting url of the plugin
http://example.com/installer/install
where installer
is the plugin name which is calling InstallController
class inside plugins/Installer/src/Controller/
directory
Now what I want to check it automatically and redirect user to the Installation interface if database connection couldn't be established.
For that I have written a function inside InstallController
of plugin's controller
public function installationCheck() {
$db = ConnectionManager::get('default');
if(!$db->connect()) {
if(Configure::read('Database.installed') == true) {
$this->Flash->error(__("Database connection couldn't be established. Please, re-configure it to start the application"));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__("Please configure your database settings for working of your application"));
return $this->redirect(['action' => 'index']);
}
}
return true;
}
Now the Question.
What is the easiest way to call this method from /app/src/Controller/AppController.php
file of the main application?
Simple answer, you don't!
Shared controller logic belongs either in
AppController
itself, a Component or a Trait. TheAppController
should never being accessing methods defined in other controllers, these shouldn't be made accessible to it.For what you're doing you probably want to do this in a component that you can load via your
AppController
or the relevant controller.So your component would look something like:-
Which you would then load in the relevant controller:-
Then you can use the component's method from the controller like:-