Thursday, February 26, 2026

Steps to set up a Modules directory in CI 4

 To add a modules directory in CodeIgniter 4, you need to create the directory in your project's root and configure the autoloader to recognize a new namespace for it. This allows you to organize application components into modular, self-contained units.

Steps to set up a Modules directory
  1. Create the Modules directory: In your project's root directory (alongside the apppublic, and system folders), create a new folder named Modules (or modules, but capitalization must be consistent).
  2. Configure Autoloading: Open the app/Config/Autoload.php file and add the Modules namespace to the $psr4 array.
    php
    // In app/Config/Autoload.php
    
    public $psr4 = [
        APP_NAMESPACE => APPPATH, // For custom namespace
        'App'         => APPPATH, // To ensure filters, etc still found,
        'Config'      => APPPATH . 'Config',
        'Modules'     => ROOTPATH . 'Modules', // Add this line
    ];
    
    Note: ROOTPATH refers to your project's root directory.
  3. Create a sample module structure: Inside the Modules folder, create a directory for your specific module (e.g., Blog). Inside the Blog module folder, you can mirror the structure of the main app folder with its own ControllersModelsViewsConfig, etc..Example structure:
    /
    ├── app/
    ├── public/
    ├── system/
    ├── Modules/
    │   ├── Blog/
    │   │   ├── Config/
    │   │   ├── Controllers/
    │   │   │   └── Blog.php
    │   │   ├── Models/
    │   │   └── Views/
    ...
    
  4. Define a Controller with the correct namespace: In your module's controller file (e.g., Modules/Blog/Controllers/Blog.php), ensure the namespace matches your configuration.
    php
    <?php namespace Modules\Blog\Controllers;
    
    use App\Controllers\BaseController;
    
    class Blog extends BaseController
    {
        public function index()
        {
            echo 'Hello from the Blog Module!';
        }
    }
    
  5. Set up Routing: You can define routes for your module in app/Config/Routes.php or create a separate routes file within the module itself that is automatically discovered. To use module-level routes, you must ensure the main application's route file is set to discover them, and define the routes with the full namespace in the module's Config/Routes.php file.For a simple route in app/Config/Routes.php to the example above:
    php
    $routes->get('/blog', 'Modules\Blog\Controllers\Blog::index');
    
For detailed official documentation on Code Modules and auto-discovery, refer to the CodeIgniter User Guide

No comments:

Post a Comment