drquincy — 2013-08-11T04:13:38-04:00 — #1
I'm quite new to namespaces though I am now sold on the idea and think they're excellent. My main gripe was though that the scope of a use statement was only in the file it was called. So, in my current project outside of the bootstrap file I have loads of fully qualified namespaces. E.g.
$object = new \\Vendor\\Package\\Class($parameter);
Not that it would happen often but if I renamed the Package to Package2 I would have to go through my code and rename \Vendor\Package\ to \Vendor\Package2\.
I have just found out as of 5.3 (which I'm using) you can call classes through variables—including namespaces. So I guess I could do something like:
$package = '\\Vendor\\Package\\\\';
$currentPackage = $package . 'Class';
$object = new $currentPackage($parameter);
I'm interested to know if you think this is a good idea or not. My gut tells me to avoid this for readability but was interested to know if others were using this. Of course, if you ever renamed a class you'd be stuck updating everything anyway.
ahundiak — 2013-08-15T16:21:33-04:00 — #2
IMHO opinion php namespace should be used they way they were intended to be and there is not much point in trying to get them work in some other fashion. Just makes your code more confusing and slower.
In most cases, just add a use statement at the top of each file for all the objects you need. Should only be a few and then use just the class name in your code.
$someClass = new SomeClass();
If you do end up with a big refactor job then at least you only need to change the user statements.
Consider also using composer. http://getcomposer.org/doc/00-intro.md
Even if you are not yet using any third party libraries composer will give you a nice autoloader for free so you won't need things like \Vendors. Your namespace's will be shorter and more flexible.
drquincy — 2013-08-16T05:50:37-04:00 — #3
Thanks for the link - great reply!