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
- Create the Modules directory: In your project's root directory (alongside the
app,public, andsystemfolders), create a new folder namedModules(ormodules, but capitalization must be consistent). - Configure Autoloading: Open the
app/Config/Autoload.phpfile and add theModulesnamespace to the$psr4array.Note:ROOTPATHrefers to your project's root directory. - Create a sample module structure: Inside the
Modulesfolder, create a directory for your specific module (e.g.,Blog). Inside theBlogmodule folder, you can mirror the structure of the mainappfolder with its ownControllers,Models,Views,Config, etc..Example structure: - 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. - Set up Routing: You can define routes for your module in
app/Config/Routes.phpor 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'sConfig/Routes.phpfile.For a simple route inapp/Config/Routes.phpto the example above:
For detailed official documentation on Code Modules and auto-discovery, refer to the CodeIgniter User Guide
No comments:
Post a Comment