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'