Global variables are generally considered bad practice unless absolutely necessary, so I am looking at alternative ways to achieve some functionality.
We are currently working on a CMS system in PHP, and wish to allow other developers to write modules easily for the CMS. We have defined a CMS class as follows:
class CMS
{
public $version;
public $sitename;
public $siteurl;
public $tbl_prefix;
function __construct()
{
}
function RegisterModule()
{
}
}
Now, we would like to generate an instance of CMS, and make it accessible to the developer (and all modules and core files) through a variable: $_cms. Since we are not able to use constant variables for objects in PHP, and using a Singleton pattern provides clumsy syntax to access the instance (i.e. CMS::GetInstance()->RegisterModule()), is there any way to achieve what we want without defining a global variable containing an instance of CMS?
Ideally, we are looking for something like the following syntax:
_cms->RegisterModule(); or $_cms->RegisterModule();, with the former being preferred.
Require plugins to be coded as classes, which either
extendtheCMSclass or accept it as a parameter to their constructor. That’s also known as Dependency Injection and is just about the cleanest interface you can get.Requiring plugins to be classes also makes it really clean and easy to include them from your app, since they’re self-contained and can easily follow specific naming and interface conventions.