关于 Laravel 的 url 辅助函数
url辅助函数
- 在 laravel 中有一个辅助函数
url()
- 它的作用是通过 path 就能生成网站对应的 url
遇到的问题
- 在我博客模板中,我想将一个连接通过 url 函数来生成对应的 url ,作为一个 a 链接
- 但是我的路由大概是这样
/articles/{id}/edit
-
通过追踪对应的源代码,我发现 url 函数的实现,是直接将
hostName
和path
以及“参数”进行拼接public function to($path, $extra = [], $secure = null) { // First we will check if the URL is already a valid URL. If it is we will not // try to generate a new one but will simply return the URL as is, which is // convenient since developers do not always have to check if it's valid. if ($this->isValidUrl($path)) { return $path; } $scheme = $this->getScheme($secure); $extra = $this->formatParameters($extra); $tail = implode('/', array_map( 'rawurlencode', (array) $extra) ); // Once we have the scheme we will compile the "tail" by collapsing the values // into a single string delimited by slashes. This just makes it convenient // for passing the array of parameters to this URL as a list of segments. $root = $this->getRootUrl($scheme); if (($queryPosition = strpos($path, '?')) !== false) { $query = substr($path, $queryPosition); $path = substr($path, 0, $queryPosition); } else { $query = ''; } return $this->trimUrl($root, $path, $tail).$query; }
- 文件路径是
/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php
- 在我看来,这里的
url()
函数应该实现不了这种 url 的获取吧 - 欢迎各位交流一下你们的实现 ^^
本作品采用《CC 协议》,转载必须注明作者和本文链接
@bing8u 额,可能你没注意到上面所写的需求,不是相对路径的问题:
需要将id对应的参数替换进去,例如我还尝试这样做
url('articles/id/edit', ['id'=>47740])
,希望最终运行的结果是/articles/47740/edit
显然,没什么效果...
框架用多了连PHP都不会了吧
@TimJuly 哈。。。被框架局限了
route() 了解一下
简单问题复杂化的典范