How to autoload a user-defined class in CI4?

57 Views Asked by At

I'd like to get a user-defined constants file out of the native \Config\Constants.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

There are 2 best solutions below

2
steven7mwesigwa On

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;
3
b126 On

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

in Config\Constants.php

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

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