Reputation: 3248
I'm working on a plugin system for my CMS, inside my CMS I use namespaces a lot.
What I would like to have is that the developers of the plugins don't have to use namespaces inside their plugin, because they can be very complicated for developers who doesn't have used namespaces before. The main problem with the namespaces is the events which can be registered. Right now, plugin developers have to load an Event class using use \events\Event;
, and if they just import the class they are still not able to use new Event();
because it uses namespaces. What I would like to have is that they can just use new Event();
(The class itself would be autoloaded by the CMS's auto loader, so no include required).
So basically, I would like to have namespaces disabled in certain classes or files. So new \events\Event();
will just look like new Event();
without removing the namespace events;
from the Event
class.
I hope I explained it clear, I'm not the best in explaining this kind of stuff.
Upvotes: 1
Views: 3130
Reputation: 874
AFAIK it is not possible, but if you use a loader that includes the needed files so that a plugin author could include a class with loader::load('someclass');
you can let the loader return the full classname with namespace and the plugin could use it:
$em_classname = Loader::load('eventmanager');
//dymamic use
$em = new $em_classname;
$em->registerEvent();
//static use
$em_classname::registerEvent();
For dynamic use you could even return an instance of the class instead of the class name.
Upvotes: 1
Reputation: 437584
No. In other words, this won't work:
namespace Foo {
class Event {}
include('plugin.php'); // plugin.php cannot just do new Event();
}
That shouldn't be a problem really, since your CMS's plugin development documentation should be clear about the namespace usage and plugin developers would simply need to write something like
use Plugin\Namespace\Events\MyEventType;
to refer to MyEventType
without needing to qualify it. Surely that's not too much to ask of plugin authors?
Upvotes: 2
Reputation: 173642
I'm not sure if I understand completely, but to run code in "global" namespace, you can do this:
namespace {
// this runs in global namespace
}
See also: Defining multiple namespaces in the same file
Upvotes: 1