0

我为 CakePHP 3.4.* 编写了一个插件。

该插件将检查是否已设置数据库配置,如果没有,则您可以通过 GUI 界面移动用户来设置数据库配置,就像 wordpress 一样。

该插件运行良好,但必须通过访问插件的 url 手动加载

http://example.com/installer/install

在目录installer中调用InstallController类的插件名称在哪里plugins/Installer/src/Controller/

现在我想自动检查它并在无法建立数据库连接时将用户重定向到安装界面。

为此,我在InstallController插件的控制器中编写了一个函数

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;
}

现在的问题。

/app/src/Controller/AppController.php从主应用程序的文件中调用此方法的最简单方法是什么?

4

2 回答 2

2

简单的回答,你没有!

共享控制器逻辑AppController本身属于ComponentTrait。不应该访问其他控制器中定义的AppController方法,它们不应该被它访问。

对于您正在做的事情,您可能希望在可以通过您的AppController或相关控制器加载的组件中执行此操作。

所以你的组件看起来像: -

<?php
namespace Installer\Controller\Component;

use Cake\Controller\Component;

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

然后将其加载到相关控制器中:-

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

然后您可以使用控制器中的组件方法,例如:-

$this->Install->installationCheck();
于 2017-05-17T18:56:38.420 回答
0

你不应该那样做!

如果您需要访问另一个控制器,我建议您将该功能移至Component,这是控制器之间共享的逻辑包。

于 2017-05-17T18:01:11.093 回答