SilverStripe 通过 init() 设置控制器 $url_handler

SilverStripe setting controller $url_handler through init()

是否可以通过 init() 函数设置 (ContentController's) $url_handlers,如下所示?

public function init() {
    parent::init();

    $this::$url_handlers = array(
        '' => 'index',
        '$Project' => 'getProject'
    );
}

我问是因为我没有调用函数,而是得到了 404,而当 'hardcoding' $url_handlers 以常规方式 private static $url_handlers = ... 代码工作时很好,函数被调用。

$url_handlers 属性 实际上是 SilverStripe 术语中的 configuration property。这意味着当您刷新缓存清单时,将重建并缓存配置。

可以 init 更新它,但是您需要使用 the configuration API 来完成它,因为到时候您的 init 方法被称为配置清单已经被解析。为此,修改 self::$url_handlers 属性 不会有任何效果。

这是一个例子:

public function init()
{
    parent::init();

    Config::inst()->update(
        __CLASS__,
        'url_handlers', 
        array(
            '' => 'index',
            '$Project' => 'getProject'
        )
    );
}

作为参考,here's the point 其中 RequestHandler::findAction 查看定义的 $url_handlers 值的配置清单。