Skip to content

Instantly share code, notes, and snippets.

@hafriedlander
Last active July 27, 2016 22:30
Show Gist options
  • Save hafriedlander/908b5ee405e70da4c4cb89bfc828bb8b to your computer and use it in GitHub Desktop.
Save hafriedlander/908b5ee405e70da4c4cb89bfc828bb8b to your computer and use it in GitHub Desktop.
Example showing proposed dynamic referencing of "Page" class namespace in SilverStripe 4
<?php
namespace Foo;
class Page {
function whoami() {
echo __CLASS__;
}
}
<?php
// This is the equivalent of `$project`, but for the namespace Page lives in
$appNamespace = "Foo";
// This is a fake PSR4 autoloader - normally composer would provide
spl_autoload_register(function ($class_name) {
$filename = str_replace('\\', '/', $class_name) . '.php';
if (file_exists($filename)) {
include $filename;
return true;
}
return false;
});
// This would normally be in Core.php or something like that.
spl_autoload_register(function ($class_name) {
global $appNamespace;
if ($class_name == '__App\Page') {
class_alias("$appNamespace\Page", '__App\Page');
return true;
}
return false;
});
// Here we reference _App\Page, and the autoload dynamically creates the
// alias to Foo\Page
class BlogPage extends __App\Page {
}
// We then create one and call the base class' whoami method to show
// that __CLASS__ isn't affected by the class_alias
$b = new BlogPage();
$b->whoami();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment