Laravel使用名爲外觀設計模式,它基本上是爲實例化對象的別名,所以你可以用這種方式:
URL::to('string');
而不是
$url = new URL;
$url->to('string');
乘坐看看你的app/config/app.php,你會看到指向Facade的URL別名:
'URL' => 'Illuminate\Support\Facades\URL',
如果你看一下門面,你會看到它的真正的「內部」的名字(「URL」),在IoC容器:
protected static function getFacadeAccessor() { return 'url'; }
這種「URL」對象由服務提供者實例某個地方,這個人是綁定到IoC容器中Illuminate\Routing\RoutingServiceProvider
:
/**
* Register the URL generator service.
*
* @return void
*/
protected function registerUrlGenerator()
{
$this->app['url'] = $this->app->share(function($app)
{
// The URL generator needs the route collection that exists on the router.
// Keep in mind this is an object, so we're passing by references here
// and all the registered routes will be available to the generator.
$routes = $app['router']->getRoutes();
return new UrlGenerator($routes, $app->rebinding('request', function($app, $request)
{
$app['url']->setRequest($request);
}));
});
}
而且那裏,你可以看到,「網址」,其實,UrlGenerator
->(http://laravel.com/api/4.1/Illuminate/Routing/UrlGenerator.html)。
這裏的to()
方法:
/**
* Generate a absolute URL to the given path.
*
* @param string $path
* @param mixed $extra
* @param bool $secure
* @return string
*/
public function to($path, $extra = array(), $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);
$tail = implode('/', (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);
return $this->trimUrl($root, $path, $tail);
}
這是在開始有點混亂,但你要記住:
1)查找的別名。
2)找到Facade並獲取真實的內部名稱。
3)找到ServiceProvider找到真實的類。
很大的問題! – Rafael