0

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?

2 Answers 2

2

Simple answer, you don't!

Shared controller logic belongs either in AppController itself, a Component or a Trait. The AppController 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:-

<?php
namespace Installer\Controller\Component;

use Cake\Controller\Component;

class InstallComponent extends Component
{
    public function installationCheck()
    {
        // Method's logic
    }
}

Which you would then load in the relevant controller:-

public function initialize()
{
    parent::initialize();
    $this->loadComponent('Installer.Install');
}

Then you can use the component's method from the controller like:-

$this->Install->installationCheck();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, implemented in my plugin.
0

You should not Do that!

If you need to access another controller I recommend you to move that functionality to a Component, that are packages of logic that are shared between controllers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.