首页 > 解决方案 > Codeigniter 4:创建模块

问题描述

我正在尝试在 Codeigniter 4 中创建模块以使用 HMVC。我尝试遵循此用户指南https://codeigniter4.github.io/userguide/general/modules.html,但无法使其正常工作。

我在应用程序、公共等文件夹旁边创建了一个“模块”文件夹。

添加到app/config/autoload.php

'Modules' => ROOTPATH.'modules'

在模块文件夹中,我创建了一个“Proef”文件夹,其中包含一个 Controllers 文件夹和“Proef.php”文件。

该文件包含以下内容;

    namespace App\Modules\Proef\Controllers;
    class Proef extends \CodeIgniter\Controller
    {
      public function index() {
        echo 'hello!';
      }
    }

app/config.routes.php我添加的文件中

    $routes->group('proef', ['namespace' => 'Modules\Proef\Controllers'], function($routes)
    {
        $routes->get('/', 'Proef::index');
    });

然而,以下错误仍然存​​在:找不到控制器或其方法:\Modules\Proef\Controllers\Proef::index

我错过了什么?

标签: phpcodeignitercodeigniter-4

解决方案


如果您将模块文件夹“并排”而不是放在您的应用程序文件夹下,那么您的命名空间是错误的。

所以你会有类似的东西

app/
Modules/   ==> can be modules or Modules but must be set in autoload with the same case
    Proef/
       Controllers/
           Proef.php

注意:模块可以是模块或模块,但自动加载中的相应条目必须匹配。

  1. 对于模块 'Modules' => ROOTPATH 。'模块'

  2. 对于模块 'Modules' => ROOTPATH 。'模块'

看来(根据我的有限测试)其他文件夹名称必须是第一个字母大写。这是在 Linux 上的 Apache 下。

让我们使用 Modules 作为文件夹名称,因此在Autoload.php中我们将...

$psr4 = [
    'App'         => APPPATH,                // To ensure filters, etc still found,
    APP_NAMESPACE => APPPATH,                // For custom namespace
    'Config'      => APPPATH . 'Config',
    'Modules'     => ROOTPATH . 'Modules'
];

所以你的 Proef 控制器 - Proef.php ...注意正在使用的命名空间。

<?php
namespace Modules\Proef\Controllers;
use App\Controllers\BaseController;

class Proef extends BaseController {
    public function index() {
        echo 'Hello - I am the <strong>'. __CLASS__ . '</strong> Class';
    }
}

要通过 URL 访问它,您可以将路由(Routes.php)设置为...(简单版本)

$routes->get('/proef', '\Modules\Proef\Controllers\Proef::index');

为了使它可以在其他控制器中调用...(为此我借用了Home.php

<?php namespace App\Controllers;

use \Modules\Proef\Controllers\Proef;

class Home extends BaseController
{
    public function index()
    {
        $mProef = new Proef();
        $mProef->index();

        return view('welcome_message');
    }

    //--------------------------------------------------------------------

}

在您的 URL 中 - /proef 将只产生消息 /home 将产生类消息和欢迎页面。

所以希望这能帮助你解决这个问题。其乐无穷 :)

在旁边:

您可以将模块文件夹放在任何地方。为了过去,我把我的放在 app/ 下,这消除了在 Autoload.php 中添加条目的需要,因为它们属于已经定义的 app/。

命名空间和使用语句也需要适当更改。


推荐阅读