关于 Laravel 的 url 辅助函数

url辅助函数

  • 在 laravel 中有一个辅助函数 url()
  • 它的作用是通过 path 就能生成网站对应的 url

遇到的问题

  • 在我博客模板中,我想将一个连接通过 url 函数来生成对应的 url ,作为一个 a 链接
  • 但是我的路由大概是这样 /articles/{id}/edit
  • 通过追踪对应的源代码,我发现 url 函数的实现,是直接将 hostNamepath 以及“参数”进行拼接

    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 协议》,转载必须注明作者和本文链接
suhanyujie
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 5
TimJuly

框架用多了连PHP都不会了吧

sprintf('/articles/%d/edit', 1)
5年前 评论

简单问题复杂化的典范

5年前 评论
suhanyujie

@bing8u 额,可能你没注意到上面所写的需求,不是相对路径的问题:

我的路由大概是这样 /articles/{id}/edit

需要将id对应的参数替换进去,例如我还尝试这样做url('articles/id/edit', ['id'=>47740]),希望最终运行的结果是/articles/47740/edit
显然,没什么效果...

5年前 评论
suhanyujie

@TimJuly 哈。。。被框架局限了

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!