0
votes

I'm trying to rewrite an OO PHP site (that loosely follows an MVC structure) so it uses namespaces - and want to follow PSR-0.

In the current site I have a class (called APP) which is full of static methods that I call all over the place to handle things such as getting config data eg; APP::get_config('key').

Obviously with namespacing, I would need to call \TheNameSpace\App::get_config('key'). I use this class frequently, so want to avoid having to prefix the namespace every time I use it. I do call methods in it from within other classes, which would usually be under a sub-namespace - so changing the namespace at the top of the file won't really work.

So, I guess my question is, what is the easiest way to have a 'global' class with methods that I can call anywhere without having to prefix with the namespace each time?

3
This has nothing to do with mvc or oop. You are just another person trying to make object-oriented-looking code while doing procedural programming. - tereško
And if you want to have a global class, why not put it in the global namespace? Remember that they are (actually) meant to eschew identifier conflicts, not for mercilessly wrapping everything without cause. - mario
Essentially this is bad design - you should be injecting dependencies into the objects that need them, not calling an outside "god" class to fetch them. - prodigitalson

3 Answers

0
votes
namespace Foo;
use Bar;

Then you do not have to do \Bar\fn

So in your case:

namspace Foo;
use TheNameSpace\App;

App::get_config('blah')
0
votes

Read the section in the php manual on using/aliasing namespaces.

http://www.php.net/manual/en/language.namespaces.importing.php

You can exclude the namespace by using "use". You can name it whatever you want.

use TheNamespace\App as App //You can name it anything here
App:config('key');
0
votes

At top of your scripts add

use TheNameSpace\App as MyApp

for example. You can then use it like

app = new MyApp();

in your scripts. Of course you needn't to use an alias here. Just

use TheNameSpace\App
app = new App();

will work, too.

A global class that's implementing this one is bad style and you shouldn't do it like this:

class MyApp extends TheNameSpace\App { }

....
myApp = new MyApp();