I have an idea that could be useful with dealing with namespaces and
auto-loading include files.
Basically, a new function could exist, called
spl_autoload_include_register, spl_autoload_namespace_register or
similar. The callback passed to this function will get called whenever
a class that is not currently defined is used, just like with
spl_autoload_register. Instead of the callback doing the work to
include the file, the callback of this function will return the filename
of the file to include, or return FALSE
if it elects not to handle the
class name.
If FALSE
is returned, PHP would continue to the next registered
autoloader.
If a filename is returned, PHP will automatically include that file.
Before the file is actually loaded/executed, PHP will set the namespace
of the included file to the namespace of the class being accessed. A
file loaded in this manor does not need to define an explicit
namespace. If it does, it must do so at the top of the file and that
will override the initial namespace.
This shows what I mean:
classes/myclass.php
<?php
// no need to declare the namespace
class MyClass {
public static function action() { print __NAMESPACE__;
Drivers\MyDriver::action();}
}
classes/drivers/mydriver.php
<?php
// no need to declare the namespace
class MyDriver {
public static function action() { print __NAMESPACE__; }
classes/bootstrap.php
<?php
// used to directly set __NAMESPACE__ used later since the
// autoloader isn't registered at this point
namespace MyNamespace;
spl_autoload_include_register(function($classname){
if(substr($classname, 0, strlen(__NAMESPACE__) + 1) ==
NAMESPACE . '\') {
return DIR . '/' . str_replace('\', '/',
strtolower(substr($classname, strlen(NAMESPACE) + 1))) . '.php';
} else {
return FALSE;
}
});
main.php
<?php
include 'classes/bootstrap.php';
MyNamespace\MyClass::action();
output
MyNamespace
MyNamespace\Drivers
In this example, none of the files that are part of the namespace must
explicitly declare so in the file. The bootstrap file for the namespace
registers the autoload include function that returns the filename to
use, and PHP automatically sets the namespace before loading the file.
This allows a way for developers to create a form of a namespace search
path, which can already be done, while removing the requirement to
explicitly state the namespace in each file. Because a callback is
used, the developer can also use whatever naming convention for the
file, whether to use the same case as the class name or to user
lowercase, what extensions to use, and so on. Because the callback
returns a filename, PHP internals code can automatically set the
namespace of the included file before including it, something that can't
be done if the callback directly included the file.
Thanks,
Brian Allen Vanderburg II