Friday, March 13, 2015

Use Laravel Contracts to Build a Laravel 5 Twig Package

Laravel 5 is finally out, and with all the awesome features it brings. One of the new architectural changes is the new Contracts Package. In this article we are going to understand the reasoning behind this change and try to build a practical use case using the new Contracts.


Laravel


What Is a Contract


A contract is an interface that defines a behaviour. Let’s take this definition from [Wikipedia](http://ift.tt/1AvgZsV).



In object-oriented languages, the term interface is often used to define an abstract type that contains no data or code, but defines behaviors as method signatures.



With that being said, we use interfaces to extract the object behaviour from a class to an interface and only depend upon the definition. In Laravel’s IoC container you can bind an interface to an implementation.



$this->app->bind('App\Contracts\EventPusher', 'App\Services\PusherEventPusher');

Now every time you resolve the EventPusher interface from the container, you will receive a Pusher implementation. If you decide to switch to another service like Fanout, you only need to change the binding.



$this->app->bind('App\Contracts\EventPusher', 'App\Services\FanoutEventPusher');

Most of Laravel core services now are extracted to a contract, and if you want for example to override the Illuminate/Mail service, you can implement the Illuminate\Contracts\Mail contract and define the necessary methods and add it a s a provider.


Continue reading %Use Laravel Contracts to Build a Laravel 5 Twig Package%




by Younes Rafie via SitePoint

No comments:

Post a Comment