用「URL 空间 + 方案」统一管理 URL 的生成与解析:前缀隔离、历史 301、PHPCMS v9 风格规则语法。官网的
/、/features.html、/blog/hello.html都出自它。
安装
composer require wiseadmin/wise-url
php think migrate:runextra.think.services 注册 wise\url\UrlServiceProvider;配置发布为 config/wise-url.php;静态资源发布到 public/statics/plugins/wise-url。
Url 静态类
wise\url\Url 是 final 静态类(不是 think\Facade):
$ctx = Url::context('wisecms', 0, '/cms/'); // app, siteId, prefix
$path = Url::pathFor($ctx, 'content', $content); // 相对路径
$to = Url::toFor($ctx, 'content', $content); // 完整 URL
$hit = Url::resolve('/cms/123.html', 0, ''); // 解析:实体 / 401 / 410其余常用:path() / to()(简化签名)、extend(EntityProviderInterface)、preset()、scheme() / schemes()、space() / spaces()、generator() / dispatcher()、config()、reset()。
前缀是唯一隔离键,app + site_id + prefix 收敛成 UrlContext。插件只贡献"实体类型 + token 取值",不自己拼 URL:
// 在 ServiceProvider::boot() 里注册一次
\wise\url\Url::extend(new ContentUrlProvider());配置里必须动的两处
config/wise-url.php 的关键节:enabled、web(enable/app/prefix/groups.front/admin)、space(enable/scheme/default_preset/allowed_hosts/reserved_prefixes)、mode(stateless|tracked|indexed,默认 tracked)、suffix、token_secret / token_ttl=600、shape.catdir_max_depth、history、fallback、presets(system.html / system.directory / system.archive)。
- 多机部署必须显式配
token_secret:否则各机器的runtime/wise-url.secret不同,方案切换的确认令牌无法互通,表现是"在 A 机preview、B 机switch失败"。 space.allowed_hosts不配就是任意域名可命中:host为空的空间是兜底空间,生产要么绑定站点域名,要么配这个白名单,否则别人拿你的 IP 访问也能命中同一套规则。
8 条命令
php think wise:url:rules # 列出激活方案与规则
php think wise:url:check # 结构校验
php think wise:url:diagnose # 诊断(前缀/规则/命中问题)
php think wise:url:preview <target> # 出切换预览与 confirmToken
php think wise:url:switch <target> [--dry-run]
php think wise:url:rebuild # 重建 URL 索引
php think wise:url:cleanup [--apply] # 清理失效索引
php think wise:url:space:doctor # 空间体检全部支持 --json,永不交互。退出码:0 成功 / 1 参数或环境错误 / 2 校验失败 / 3 需要人工确认。
切换方案必须两步:先 preview 拿 confirmToken,再 switch;跳过校验会返回 URL_CONFIRM_REQUIRED。这是防止"手滑改坏全站 URL"的唯一闸门。
能力边界
包只提供两个无框架的 ES Module,不含 UI、不提供控制器,也不生成静态 HTML、不做静态/动态双规则。
两件宿主需要自己接的事:兜底路由要调 \wise\url\http\CatchAllRoute::register(...);实体模型用 TracksUrlAlias Trait 记账历史 301(否则 history 表是空的,旧地址不会跳转)。
三个容易搞错的认知
一、"装完就自动接管 URL"。需要宿主注册兜底路由 + 配空间,包本身不注册控制器。
二、"mode 随便选"。tracked 会写索引表(支持历史与清理),stateless 完全不落库——上线后改 mode 会影响索引表数据。
三、"切换是单机行为"。多机必须配 token_secret,否则令牌不互通。
自查:php think wise:url:rules 列出激活方案与规则;php think wise:url:diagnose 报的每条问题都能逐条修;访问旧地址应 301 到新地址。框架侧概览见URL 与路由规则。