An explanation of the use of IOC containers in the Laravel framework

Source: Internet
Author: User
Recently in learning Laravel, just learned the IOC container, but found that the information on the Internet is less, so will learn from the summary, the following this article mainly to you about the Laravel Learning Tutorial IOC container related information, the need for friends can refer to the following to see it together.

Objective

Laravel uses the IOC (inversion of control, which controls the inversion, which is a design pattern that can be viewed first) container this powerful tool for managing class dependencies. Dependency Injection (also a design pattern, typically used to implement IOC) is a method of not having to write fixed code to handle dependencies between classes, instead, these dependencies are injected at runtime, allowing greater flexibility in handling dependencies.

Understanding the Laravel IOC container is necessary to build a powerful application and also helps Laravel the core itself. The following words do not say much, come together to see the detailed introduction.

Basic Use Cases

Binding a type to a container

The IoC container has two methods to resolve dependencies: through closure callbacks or automatic parsing. First, let's explore the closure callback. First, you need to bind a "type" into the container:


App::bind (' foo ', function ($app) {return new FooBar;});

Get a type from the container


$value = App::make (' foo ');

When App::make the method is executed, the closure function is executed and the result is returned.

Bind a "shared" type to a container

Sometimes you just want to process the type that is bound to the container once, and then the next thing you get from the container should be the same instance:


App::singleton (' foo ', function () {return new FooBar;});

Binds an already existing type instance to the container

You can also use the instance method to bind an already existing object interface to the container:


$foo = new Foo; App::instance (' foo ', $foo);

Where to register bindings?

IOC bindings, much like event handlers or route filtering, are usually done after "bootstrap code". In other words, they are ready to process the request in your application, that is, before a route or controller is actually executed. As with other boot code, the start file is typically registered as an IOC binding method. In addition, you can create a app/ioc.php (file name is not necessarily the same) files and include it in the start file.

If your application has a lot of IOC bindings, or if you want to split the IOC bindings into different files based on different classifications, you can try to bind in the service provider (see below)

Automatic parsing

Obtain a class

The IOC container is powerful enough to get classes in many scenarios without requiring any configuration. For example


Class FooBar {public function __construct (Baz $baz) {  $this->baz = $baz;}} $fooBar = App::make (' FooBar ');

Note: Although we do not register the Foobar class in the container, the container can still get the class, or even automatically inject Baz dependency!

When a type is not bound to a container, the IOC container uses the PHP reflection tool to examine the class and read the type hints of the constructor. With this information, the container can automatically build class instances.

Binding an interface implementation

In some cases, however, a class might rely on an interface implementation rather than a "concrete class." When this is the case, the App::bind method must notify the container to inject which interface implementation:


App::bind (' Userrepositoryinterface ', ' dbuserrepository ');

Now consider this controller:


Class Usercontroller extends Basecontroller {public function __construct (Userrepositoryinterface $users) {  $this-& Gt;users = $users; }}

Since we bind userrepositoryinterface to a specific class, Dbuserrepository will be automatically injected into the controller when the controller is created.

Actual Use Cases

Laravel provides several ways to enhance application extensibility and testability using IoC containers. A major example is the acquisition of a controller. All controllers are obtained through the IoC container, which means that the dependent type hints can be made in the controller construction method and they will be injected automatically.

Type hints for controller dependencies


Class Ordercontroller extends Basecontroller {public function __construct (orderrepository $orders) {  $this orders = $orders; Public Function GetIndex () {  $all = $this->orders->all ();  Return View::make (' orders ', compact (' All ')); }}

In this example, the orderrepository will be automatically injected into the controller. means that when a unit tests a mock request, orderrepository will bind to the container and inject it into the controller, allowing painless interaction with the database layer.

Other examples of IoC use

Filters, composers, and event handles can also be obtained from the IOC container. When registering them, simply give them the class name they use:


Route::filter (' foo ', ' Foofilter '); View::composer (' foo ', ' Foocomposer '); Event::listen (' foo ', ' Foohandler ');

Service Provider

A server provider is an effective way to register a set of related IoC to a single path. Consider them as a way to boot components. In the server provider, you can register your custom authentication drive, register the application warehouse class with the IoC container, or even customize the Artisan command.

In fact, most core Laravel components contain service providers. All applications registered in the service provider are listed in the providers array of the app/config/app.php configuration file.

Defining a service Provider

To create a service provider, simply inherit the Illuminate\support\serviceprovider class and define a register method:


Use Illuminate\support\serviceprovider;class Fooserviceprovider extends ServiceProvider {public Function register () { c0/> $this->app->bind (' foo ', function ()  {   return new Foo;  }})

Note: in the Register method, the application accesses the IoC container by $this the->app property. Once you have created the provider and want to register it in the application, simply put it into the providers array in the app configuration file.

Run-time Registry service provider

You can also use App::register the method to register the service provider at run time:


App::register (' Fooserviceprovider ');

Container Events

Register for an event listener

The container fires an event each time the object is fetched. You can listen to the event by using the resolving method:


App::resolvingany (function ($object) {//}); App::resolving (' foo ', function ($foo) {//});

Note: The object being fetched will be passed into the callback function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.