Skip to content

Instantly share code, notes, and snippets.

@wilr
Created February 6, 2018 20:35
Show Gist options
  • Save wilr/5c74e1ba939ef240331052092c2889fa to your computer and use it in GitHub Desktop.
Save wilr/5c74e1ba939ef240331052092c2889fa to your computer and use it in GitHub Desktop.
Snippet for namespaced SilverStripe Pagetypes to find their controller in a different namespace.
<?php
namespace App\Project\Model;
use SilverStripe\Core\ClassInfo;
use SilverStripe\CMS\Model\SiteTree;
use App\Project\Control\PageController;
class Page extends SiteTree
{
/**
* Returns the controller class for this page. If a subclass of the page
* controller exists, use that. Otherwise default to the base namespaced
* controller.
*
* This is required as the SiteTree getControllerName doesn't handle cross
* namespace (i.e \Model\ vs \Control).
*/
public function getControllerName()
{
$current = static::class;
$ancestry = ClassInfo::ancestry($current);
$controller = null;
while ($class = array_pop($ancestry)) {
if ($class == self::class) {
break;
}
if (class_exists($candidate = sprintf('%sController', $class))) {
$controller = $candidate;
break;
}
$candidate = sprintf('%sController', str_replace('\\Model\\', '\\Control\\', $class));
if (class_exists($candidate)) {
$controller = $candidate;
break;
}
}
if ($controller) {
return $controller;
}
return PageController::class;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment