Reputation: 53198
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.
Upvotes: 1
Views: 138
Reputation: 3065
I don't know if I am making seance though let me put my view If i have such a problem I would use magic method __call() will be applicable to the files other developer will work on and it will look like in one of my code file
function __call($name,$params)
{
if($name == 'RegisterModule')
{
$cms = myRegisty::get('cms');
$cms->RegisterModule($params);
}
}
while at module registation it will look like
RegisterModule($params);
hope it helps :) I think your consern is about the syntax and want more keen looking code so this was my point
Upvotes: 0
Reputation: 522081
Require plugins to be coded as classes, which either extend
the CMS
class 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.
class MyPlugin {
public function __construct(CMS $cms) {
...
}
}
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.
Upvotes: 4
Reputation: 1054
You could use a static class redirecting the method calls to the GetInstance()-Methods.
Is it neccessary to have an instance, or would it be possible to declare the CMS-class as static?
http://www.php.net/manual/en/language.oop5.static.php
Upvotes: 0