Welcome Guest, Not a member yet? Register   Sign In
CodeIgniter 4 Modules -How I am doing it [Recommendations Required]
#1

;Hello there.
I have been using CodeIgniter 4 since its release. But of late I have started to dislike the idea of defining module routes in the main Config/Routes.php file.
I came up with a hack, much like the CI3 HMVC/MX library, to auto-load modules Routes.php in a specific directory;

PHP Code:
$di = new RecursiveDirectoryIterator(FCPATH.'Modules'FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($diRecursiveIteratorIterator::SELF_FIRST);

foreach ( 
$ri as $file ) {
    if(!
$file->isDir() && isset(explode('Config/Routes.ph'$file)[1])) {
        include(
$file);
    }



Modules is a directory at the root of the CI4 instance and has its namespace defined in the Autoload.php as bellow

PHP Code:
    public $psr4 = [
        ...
        
'Modules'      => FCPATH 'Modules'
    
]; 

Now all modules directories go in the Modules directory; for example module Admin would have the following structure:


Modules
      Admin
           Config
                   Routes.php  //Here define routes for this module
           Controllers
                 ControllerName.php //Namespace is \Modules\Admin\Controllers
                 ControllerTwo.php
           Models
           ....
     AnotherModule
            Config
                   Routes.php //routes for AnotherModule module
            Controllers
             .......



For this method to work, All classes should be under the \Modules\ namespace; for example
Code:
\Modules\Admin\Controllers
for controllers or
Code:
\Modules\Admin\Models
for models

Any feedback, suggestions and recommendations will be highly appreciated.
Reply


Messages In This Thread
CodeIgniter 4 Modules -How I am doing it [Recommendations Required] - by Bennito254 - 10-01-2020, 01:32 AM



Theme © iAndrew 2016 - Forum software by © MyBB