Google Groups

Making better use of namespaces

Sam Minnée Mar 26, 2012 4:34 PM
Posted in group: SilverStripe Core Development
So, if we don't need to support PHP 5.2, we can make use of namespaces.  There are a few issues to work through.  Here are the ones that I can think of:

1) Backwards compatibility.

Let's assume that we move DataObject to silverstripe\framework\model\DataObject

A user's codebase might contain this:

class MyClass extends DataObject {

By default DataObject won't be discovered.  However, if we call class_alias("silverstripe\\framework\\model\\DataObject", "DataObject") in our autoloader, then this can be preserved.  This will mean that we'd still need a manifest, but it gives us a big backward compatibility boost.

I'm pretty convinced that we *need* this feature in SS3.  However, should we deprecate this usage, or do we consider it an enlightened way of getting the best of both worlds: the reliability of namespaces with the conciseness of direct class names.  Forcing the inclusion of "use" statements in every PHP file makes things more verbose, and I'd be inclined to benefit from the fact that we have a manifest.  Perhaps we try getting use statements into things and see who much more verbose it makes code (if you're mostly referring to classes from the same namespace - a sign of low coupling - maybe it won't be such a big deal)

2) PSR-0 compliance

PSR-0 is a standard mapping between namespaces and filenames:

It seems like a good move to get our code using this, although it's not strictly necessary, given that we have the manifest.  However, moving towards PSR-0 means that the manifest could become less important, and there might be opportunities for performance enhancement here.

For classes that currently contain underscores, we could either rename the class (see (3) below) or move the class into a subfolder.  Personally, I'd rather go for the former.

3) Dealing with renamed classes

With a bit of code in our autoloader, we could deal with renamed classes (DataObjectSet -> ArrayList, FieldSet -> FieldList, etc) more elegantly than currently: we can maintain a list of class renames and make an appropriate class_alias() call in the autoloader.  These should probably throw deprecation errors, but the code will work.

We could even use a /** @oldClassName **/ annotation to define this.  It would be way of easing annotations into the framework in a place where only advanced users are going to need to deal with them.

4) What are our base namespaces?

I would suggest that we use the following for our base namespaces:


Beyond that, our current folder structure can guide us: