IoC Based Extension 使用容器进行扩展
Almost every service provider included with the Laravel framework binds objects into the IoC container. You can find a list of your application's service providers in the app/config/app.php configuration file. As you have time, you should skim through each of these provider's source code. By doing so, you will gain a much better understanding of what each providers adds to the framework, as well as that keys are used to bind various services into the IoC container.
Laravel 框架内几乎所有的服务提供者都会绑定一些对象到 IoC 容器里。你可以在 app/config/app.php 文件里找到服务提供者列表。如果你有时间的话,你应该大致过一遍每个服务提供者的源码。这么做你便可以对每个服务提供者有更深的理解,明白他们都往框架里加了什么东西,对应的什么键。那些键就用来联系着各种各样的服务。
For example, the PaginationServiceProvider binds a paginator key into the IoC container, which resolves into Illuminate\Pagination\Environment instance. You can easily extend and override this class within your own application by overriding this IoC binding. For example, you could create a class that extend the base Environment:
举个例子,PaginationServiceProvider 向容器内绑定了一个 paginator 键,对应着一个 Illuminate\Pagination\Environment 的实例。你可以很容易的通过覆盖容器绑定来扩展重写该类。比如,你可以创建一个扩展自 Environment 类的子类:
namespace Snappy\Extensions\Pagination;
class Environment extends \Illuminate\Pagination\Environment {
//
}
Once you have created your class extension, you may create a new SnappyPaginationProvider service provider class which overrides the paginator in its boot method:
子类写好以后,你可以再创建个新的 SnappyPaginationProvider 服务提供者来扩展其 boot 方法,在里面覆盖 paginator:
class SnappyPaginationProvider extends PaginationServiceProvider {
public function boot()
{
App::bind('paginator', function()
{
return new Snappy\Extensions\Pagination\Environment;
}
parent::boot();
}
}
Note that this class extends the PaginationServiceProvider, not the default ServiceProvider base class. Once you have extended the service provider, swap out the PaginationServiceProvider in your app/config/app.php configuration file with the name of your extended provider.
注意这里我们继承了 PaginationServiceProvider,而非默认的基类 ServiceProvider。扩展的服务提供者编写完毕后,就可以在 app/config/app.php 文件里将 PaginationServiceProvider 替换为你刚扩展的那个类了。
This is the general method of extending any core class that is bound in the container. Essentially every core class is bound in the container in this fashion, and can be overridden. Again, reading through the included framework service providers will familiarize you with where various classes are bound into the container, and what keys they are bound by. This is a great way to learn more about how Laravel is put together.
这就是扩展绑定进容器的核心类的一般方法。基本上每一个核心类都以这种方式绑定进了容器,都可以被重写。还是那一句话,读一遍框架内的服务提供者源码吧。这有助于你熟悉各种类是怎么绑定进容器的,都绑定的是哪些键。这是学习 Laravel 框架到底如何运转的好方法。