Silverstripe Controller 文档令人困惑

Silverstripe Controller docs confusing

根据文档,"We need to define the URL that this controller can be accessed on. In our case, the TeamsController should be visible at http://yoursite.com/teams/ and the players custom action is at http://yoursite.com/team/players/."。但是控制器定义为

<?php

    class TeamController extends Controller {

    private static $allowed_actions = array(
        'players',
        'index'
    );

    public function index(HTTPRequest $request) {
        // ..
    }

    public function players(HTTPRequest $request) {
        print_r($request->allParams());
    }
}

?>

配置:

Name: mysiteroutes
After: framework/routes#coreroutes
---
Director:
  rules:
    'teams//$Action/$ID/$Name': 'TeamController'

这是正确的吗?

TLDR;

是的,理论上是正确的。除了一个小错别字。

更长的答案

您想在访问 url http://yoursite.com/team/players/ 时查看玩家列表。这个URL有四个部分:

  1. 协议http://
  2. 域名yoursite.com
  3. 域名后的第一部分,/team
  4. 域名后的第二部分,/player

协议和域由您的网络服务器与您的 SilverStripe 安装一起解析。现在是 /team。这应该映射到您的 TeamController class。因此我们需要定义一个 route 以便 SilverStripe 知道,以 team 开头的所有内容都应该由该控制器处理。我们在 yml.config 中定义路由,我更喜欢一个单独的路由文件,例如*/mysite/_config/routes.yml':

Name: mysiteroutes
After: framework/routes#coreroutes
---
Director:
  rules:
    'team//$Action/$ID/$Name': 'TeamController'

所以任何以 'team' 开头的请求(在域之后)(请注意,在您的示例中,您有 teams,这是一个重要的打字错误,会破坏一切)路由到 TeamController class,第二个参数(在我们的示例中 "players" 作为 $Action 参数传递。TeamController 本身不知道第一部分,它只是获取您在路由中定义的其他参数。

这由 $allowed_actions 映射到您的 TeamControllerclass:

private static $allowed_actions = array(
    'players',
    'index'
);

因此直接映射到呈现输出的 players 方法。