【问题标题】:How does laravel parse routes into component parts?laravel 如何将路由解析成组件?
【发布时间】:2022-11-12 12:48:05
【问题描述】:

它变得很好奇,laravel 如何解析路由并了解哪个路由与正确的 url 匹配?例如 url 由适当的路由处理?

www.ru/post/100/comments/500

Route::get('/posts/{post}/comments/{comment}', [NameConroller::class, 'show']);

乍一看,

  1. 看来我们应该用 / 分割传入的路由(例如explode())。
  2. 然后找到第一部分以 /post 开头的所有路由
  3. 从上一段中找到的路由中,我们应该理解(如何?) /{post} 匹配任何数字。等等。

    也许有人深入研究了源代码或者只是知道它是如何工作的?知道会很有趣)

【问题讨论】:

标签: php laravel


【解决方案1】:

这一切都发生在这里https://github.com/laravel/framework/blob/9.x/src/Illuminate/Routing/RouteCollection.php#L153

Laravel 循环遍历所有路由,直到找到匹配项,在此处检查 https://github.com/laravel/framework/blob/9.x/src/Illuminate/Routing/Route.php#L328

如果您查看https://github.com/laravel/framework/blob/9.x/src/Illuminate/Routing/Matching/UriValidator.php,您会看到/posts/{post}/comments/{comment} 被编译为{^/posts/(?P<post>[^/]++)/comments/(?P<comment>[^/]++)$}sDu,并使用正则表达式进行检查

有关正则表达式的解释请看这里https://regex101.com/r/VgsiHI/1

第一个匹配的 url 是获取请求的路由

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2020-04-04
    • 1970-01-01
    • 2022-11-14
    • 2023-01-12
    • 2017-04-04
    • 1970-01-01
    相关资源
    最近更新 更多