读完这篇你会知道:
blog@article/index这种写法为什么能让宿主任意覆盖插件模板、前台路由为什么不用写plugin/前缀、以及会员页的路径为什么老是多一层。
视图 scope:三层查找
插件模板统一用 {ident}@{path} 寻址:
L1 宿主覆盖 app/view/{ident}/{path}.html
L2 插件/包视图 plugins/{ident}/view/{path}.html
L3 默认主题 app/view/default/{path}.html(回退)View::fetch('blog@article/index') 按 L1 → L2 → L3 查找。L1 的意义是让宿主能在不改插件源码的前提下改模板——这是插件能被第三方安装的前提,也是为什么禁止写绝对路径:
// 禁止:绕过 scope,宿主无法覆盖
return View::fetch(__DIR__ . '/../view/index/index.html');plugin\BaseController::bindViewScope() 干的事就一句:把 request->view_scope 设成插件标识。PluginTrait::pluginView($tpl) 则返回 "{ident}@{$tpl}",用于跨插件引用模板。
前台控制器
前台页面继承 plugin\FrontController,不是 BaseController:
namespace plugin\blog\controller;
class Index extends \plugin\FrontController
{
public function index()
{
return $this->assign(['title' => '博客首页'])->fetch('blog@index/index');
}
}FrontController::initialize() 是 pluginInitialize() → bindViewScope() → initPlugin() → parent::initialize(),上游 app\common\controller\FrontController 负责注入站点配置。
选错基类的后果是安全性的:BaseController 上挂着后台登录与 CSRF 那一套,而 FrontController 是给匿名访客用的。反过来,用 FrontController 做后台页就等于没有 RBAC。
前台默认插件由 config('app.default_plugin') 决定(IndexDispatch)。它明确禁止前台入口实例化 plugin\BaseController 与 plugin\ApiController 子类——防止后台页面或 JSON 接口通过前台 URL 被匿名读取。
路由:不加前缀,但要自带业务前缀
前台路由放 route/index.php:
Route::get('blog/index', 'plugin\blog\controller\Index@index');
// 最终 URL:/blog/index(应用名已由多应用剥离)框架不加任何前缀,所以你必须自己写业务段(blog/)。另外 route/index.php 是始终注册的(不限于是不是默认前端插件),两条规则重名时后者会覆盖前者——排查"路由被谁注册了"时先看这里。
会员前台是另一套
会员页不走上面两个基类,而是继承 plugin\member\controller\web\MemberFrontController,用 renderMember() 渲染,由 RequireMemberAuth 保护。
关键是路由前缀:写应用内相对前缀 'demo',实际 URL 才是 /member/demo/achievements。写成 'member/demo' 会变成 /member/member/demo/**——因为 member 已被多应用剥离。这个错误的表现是 404,不是 403,很容易往权限上查。
模板里的三个占位符:
| 占位符 | 指向 |
|---|---|
__THEME__/css/theme.css | 宿主主题资源 |
__PLUGIN_ASSET__/css/xxx.css | 插件资源副本 |
{$web_base}/center | 会员中心入口(不要硬编码 /member) |
模板找不到怎么查
| 现象 | 优先排查 |
|---|---|
TemplateNotFoundException | scope 名与插件标识是否一致;模板是否真在 view/{path}.html |
| 改了模板没生效 | 是否存在 L1 宿主覆盖 app/view/{ident}/{path}.html(它优先) |
| 后台页面样式错乱 | 是否误用了前台控制器,或漏了 bindViewScope() |
| 会员页 404 | 路由前缀是否多写了应用名(member/demo) |
前后台对比
| 维度 | 后台页面 | 前台页面 |
|---|---|---|
| 基类 | plugin\BaseController | plugin\FrontController |
| 权限 | RBAC + CSRF + 登录 | 通常匿名或会员鉴权 |
| 模板 | 后台布局(iframe) | 站点主题 / 会员主题 |
| 路由文件 | route/plugin.php(自动加 plugin/{ident}) | route/index.php(自带业务前缀) |
三个容易搞错的认知
一、"模板绝对路径更直接"。 直接是直接,但宿主再也覆盖不了,插件的可移植性就没了。
二、"前台路由也会被加 plugin/{ident}"。 不会,只有 route/plugin.php 加。
三、"会员页 404 是权限问题"。 多数是前缀多写了一层应用名。
验证三层解析最直接的办法:在 app/view/blog/index/index.html 放一行临时标记,刷新前台页面若看到它,说明 L1 生效;删掉标记再看插件模板是否回来。