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
Thanks to the answer of @steven7mwesigwa, I suggest this way, despite it's still inside Constants.php:
in ConfigConstants.php
Then you can use
UserConstants::YEAR
from anywhere (controllers & views).Set up a Global Constant in
app/Config/Constants.php
Usage anywhere within your application