Laravel 4.1文档如何工作?

Gra*_*col 4 php laravel laravel-4

我已经开始了解Laravel如何使用其文档以及教程和SO.但是当我尝试使用他们的API /类引用时,我一直遇到同样的问题.

例如,我已经能够像这样使用URL类:

URL::to('string')
Run Code Online (Sandbox Code Playgroud)

我从教程中学到了什么.但是,如果我查看Illuminate\Support\Facades\URL的文档,它不会列出to()方法.

相反,如果我查看Illuminate\Filesystem\Filesystem的文档,我尝试调用这样的get()方法:

$file = new Filesystem;
$file->get('lorem.txt'); 
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

Class 'Filesystem' not found
Run Code Online (Sandbox Code Playgroud)

我的问题:

  • 我怎么知道我可以使用哪些类以及我可以调用哪些方法?
  • 我在哪里可以找到这些信息?
  • 或者我只是错过了一些关于Laravel如何工作的东西?

Ant*_*iro 9

Laravel使用名为Facade的设计模式,它基本上是实例化对象的别名,因此您可以这样使用它:

URL::to('string');
Run Code Online (Sandbox Code Playgroud)

代替

$url = new URL;
$url->to('string');
Run Code Online (Sandbox Code Playgroud)

看看你的app/config/app.php,你会看到指向Facade的URL别名:

'URL' => 'Illuminate\Support\Facades\URL',
Run Code Online (Sandbox Code Playgroud)

如果您查看Facade,您将在IoC容器中看到它的真实"内部"名称('url'):

protected static function getFacadeAccessor() { return 'url'; }
Run Code Online (Sandbox Code Playgroud)

这个'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);
        }));
    });
}
Run Code Online (Sandbox Code Playgroud)

事实上,你可以看到'url'是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);
}
Run Code Online (Sandbox Code Playgroud)

开始时有点混乱,但你必须记住:

1)找到别名.

2)找到Facade并获得真正的内部名称.

3)找到ServiceProvider以找到真正的类.