gajus / director
生成相对预定义路由的URL并处理重定向的实用工具。
1.0.1
2014-10-06 17:09 UTC
Requires
- php: >=5.4
Requires (Dev)
- psr/log: 1.0.0
- satooshi/php-coveralls: dev-master
This package is not auto-updated.
Last update: 2024-09-11 11:53:19 UTC
README
生成相对预定义路由的URL并处理重定向的实用工具。
用例
使用 Router
实例生成URL。当您的URL模式在部署环境之间不同时,这很方便。
URL
Router
实例携带预定义的路由,用于构建URL。
/** * @param string $url Default route URL. */ $locator = new \Gajus\Director\Locator('http://gajus.com/'); /** * @todo Check if query string is included. * @param string $route_name Route name. * @param string $url Absolute URL. * @return null */ $locator->setRoute('static', 'http://static.gajus.com/'); # null /** * Get absolute URL using either of the predefined routes. * Requested resource path is appended to the route. * * @param string $path Relavite path to the route. * @param string $route Route name. */ $locator->url(); # http://gajus.com/ // Get URL relative to the default route: $locator->url('post/1'); # http://gajus.com/post/1 // Get URL for the "static" route: $locator->url(null, 'static'); # http://static.gajus.com/ // Get URL relative to the "static" route: $locator->url('css/frontend.css', 'static'); # http://static.gajus.com/css/frontend.css
重定向
/** * Redirect user agent to the given URL. * * If no $url is provided, then attempt to redirect to the referrer * or (when referrer is not available) to the default route. * * @see http://benramsey.com/blog/2008/07/http-status-redirection/ * @param string|null $url Absolute URL * @param int|null $response_code HTTP response code. Defaults to 303 when request method is POST, 302 otherwise. * @return null */ $locator->location(); # null (script execution terminated) // Redirect to the default path with status code 307: $locator->location(null, 307); # null (script execution terminated) // Redirect to an arbitrary URL: $locator->location('http://gajus.com'); # null (script execution terminated)
如果已发送头部信息,location
将抛出 Exception\LogicException
异常。
获取路径
url
方法的作用域是 getPath
。它用于获取当前请求URI相对于特定路由的资源路径。
// Taken from ./tests/RouterTest.php $locator = new \Gajus\Director\Locator('https://gajus.com/foo/'); $_SERVER['HTTPS'] = 'on'; $_SERVER['HTTP_HOST'] = 'gajus.com'; $_SERVER['REQUEST_URI'] = '/foo/'; $this->assertSame('', $locator->getPath()); $_SERVER['HTTPS'] = 'on'; $_SERVER['HTTP_HOST'] = 'gajus.com'; $_SERVER['REQUEST_URI'] = '/foo/bar/'; $this->assertSame('bar/', $locator->getPath()); $_SERVER['HTTPS'] = 'on'; $_SERVER['HTTP_HOST'] = 'gajus.com'; $_SERVER['REQUEST_URI'] = '/foo/bar/?foo[bar]=1'; $this->assertSame('bar/', $locator->getPath());