gimme url
The first release
gimme url是 League Route 库缺少的 URL 生成器。它能够生成命名路由的相对和绝对路径。
使用 Composer 安装gimme url :
composer install franzose/gimme-url
URL 生成器要求您提供Router
和RequestContext
实例。后者从PsrHttpMessageServerRequestInterface
实例收集信息,并用于构建命名路由的绝对路径。
<?php
use GimmeUrl RequestContext ;
use GimmeUrl Router ;
use GimmeUrl UrlGenerator ;
use Zend Diactoros ServerRequestFactory ;
$ router = new Router ();
$ router -> get ( ' /foo/{bar} ' , function () {
//
})-> setName ( ' foo_route ' );
// Let's say the request is secure and is made at example.com on 8080 port
$ request = ServerRequestFactory:: fromGlobals ( $ _SERVER , $ _GET , $ _POST , $ _COOKIE , $ _FILES );
$ context = RequestContext:: fromRequest ( $ request );
$ generator = new UrlGenerator ( $ router , $ context );
// Then you'll get this
$ generator -> relative ( ' foo_route ' , [ ' bar ' => ' 123 ' ]); // '/foo/123'
$ generator -> relative ( ' foo_route ' , [ ' bar ' => ' 123 ' , ' qux ' => ' doo ' ]); // '/foo/123?qux=doo'
$ generator -> absolute ( ' foo_route ' , [ ' bar ' => ' 456 ' ]); // 'https://example.com:8080/foo/456'
$ generator -> absolute ( ' foo_route ' , [ ' bar ' => ' 456 ' , ' qux ' => ' doo ' ]); // 'https://example.com:8080/foo/456?qux=doo'