Welcome Guest, Not a member yet? Register   Sign In
Modules constants
#1

Hey all, I am experimenting with codeigniter 4.

I am intending to recreate an old project I did with CI 3. But in the process of my analysis I decided to split of all major components in seperate modules.

Now as I am lazy and don't want to write specific namespace everytime. I was thinking of placing it inside the constants.php config file in every module. But I can not get it to work. Am I missing something?

defined('MODULE_NAMESPACE') || define('MODULE_NAMESPACE', 'Admin');
defined('MODULE_NAMESPACE_LOC') || define('MODULE_NAMESPACE_LOC', 'Modules\Admin\\');

public function index()
{
     return view(MODULE_NAMESPACE_LOC .'Views\admin');
}
Reply
#2

After some thinkering I found a way to include the specific constants I required.

I do however wonder if this is the correct approach and if there is no better way to achieve this. What I did is the following. 

In the app/config/Constants.php add the following:

PHP Code:
/**
 * --------------------------------------------------------------------
 * Include Modules Constants Files
 * --------------------------------------------------------------------
 */

if (file_exists(ROOTPATH'modules')) {
    
$modulesPath ROOTPATH.'modules/';
    
$modules scandir($modulesPath);

    foreach (
$modules as $module) {
        if (
$module === '.' || $module === '..') continue;
        if (
is_dir($modulesPath) . '/' $module) {
            
$constantsPath $modulesPath $module '/Config/Constants.php';
            if (
file_exists($constantsPath)) {
                require(
$constantsPath);
            } else {
                continue;
            }
        }
    }


And then just create a Constants.php in your modules/Admin/Config/
Add your constants and they will be loaded if they exist.
Reply
#3

Constants in CI has always been confusing for me. In CI3 I kept them in constants.php but in CI4 I have divided up the different sets of constants (for example DB table names and permission constants) in separate classes. I keep them in app/Libraries:
PHP Code:
<?php

namespace App\Libraries;

class 
Table
{

    public const badge_providers 'badge_providers';
    public const badge_templates 'badge_templates';
    public const brands 'brands';

In code I reference them with Table::brands and rely on the autoloading.
Reply
#4

(This post was last modified: 03-09-2021, 10:41 AM by ZoeF.)

Mmm I see, I do however believe constants should be in the constants file. Therefore the solution I found seems to be doing the job just fine. The thing I am wondering about is why the constants file in the modules/config folder is not beeing found automaticly.

PHP Code:
public $aliases = [
        
'constants',
        
'events',
        
'filters',
        
'registrars',
        
'routes',
        
'services',
    ]; 

For one or another reason the constants are not beeing discovered.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB