skip to Main Content

I’d like to get a user-defined constants file out of the native ConfigConstants.php from CI4

I would like to write a class like :

public class UserConstants{
    const YEAR = 2024;
    const MAX = 9999;
    const FOO = "myfoo";
}

or

class UserConstantsStaticWay
{
    private static $year;
    private static $max;
    private static $foo;

    public static function getYear():int {return self::$year;}
    public static function getMax():int {return self::$max;}
    public static function getFoo():string {return self::$foo;}
}

This would allow me to use syntax such as UserConstants::YEAR or UserConstantsStaticWay::getYear() in my Controllers or even in my Views.

In CI4, where could I define such a class?
What would be the most elegant way? in Config, Service, Library, a simple class definition or other?

And more importantly, how could I load it automatically and make it available in all Controllers and Views? Then not only in the BaseController definition.

I’m not talking about CI4's Autoload PSR4 namespaces here, but rather the old Resources CI3 Autoloader.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to the answer of @steven7mwesigwa, I suggest this way, despite it's still inside Constants.php:

    in ConfigConstants.php

    abstract class UserConstants
    {
        const YEAR = 2024;
        const MAX = 9999;
        const FOO = "myfoo";
    }
    

    Then you can use UserConstants::YEAR from anywhere (controllers & views).


  2. Set up a Global Constant in app/Config/Constants.php

    class UserConstants{
        const YEAR = 2024;
        const MAX = 9999;
        const FOO = "myfoo";
    }
    
    define("UserConstants", UserConstants::class);
    

    Usage anywhere within your application

    echo (new (UserConstants))::FOO;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search