【问题标题】:Codeigniter 4: creating modulesCodeigniter 4:创建模块
【发布时间】:2020-04-11 13:38:41
【问题描述】:

我正在尝试在 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

我错过了什么?

【问题讨论】:

    标签: php codeigniter codeigniter-4


    【解决方案1】:

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

    所以你会有类似的东西

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

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

    1. 对于模块 '模块' => 根路径。 “模块”

    2. 对于模块 '模块' => 根路径。 “模块”

    似乎(根据我的有限测试)其他文件夹名称必须 是第一个字母大写。这是在 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');
        }
    
        //--------------------------------------------------------------------
    
    }
    

    在您的网址中 - /proef 将导致只是消息 /home 将产生课程消息和欢迎页面。

    所以希望这能帮助您解决这个问题。这很有趣:)

    旁白:

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

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

    【讨论】:

      【解决方案2】:

      编辑 Proef 类中 Modules\Proef\Controllers 的命名空间

      【讨论】:

        猜你喜欢
        • 2021-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-10
        • 1970-01-01
        • 1970-01-01
        • 2014-02-15
        • 1970-01-01
        相关资源
        最近更新 更多