03.12.2015 Views

laravel4cookbook

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Packages 143<br />

43<br />

44 $provider = new EntryProvider($database);<br />

45 $archiver = new Archiver($provider);<br />

46 $archiver->archive();<br />

Woah Nelly! That’s a lot of code when compared to the first snippet; but it’s worth it. Firstly; we’re<br />

exposing so few details to the Archiver class that the entire entry dependency could be replaced in<br />

a heartbeat. This is possible because we’ve moved the database dependency out of the Archiver and<br />

into the EntryProvider.<br />

We’re also type-hinting an interface instead of a concrete class; which lets us swap the concrete<br />

class out with anything else that implements EntryProviderInterface. The concrete class can fetch<br />

the entries from the database, or the filesystem or whatever.<br />

We can test the EntryProvider class by swapping in a fake Database instance. We can test the<br />

Archiver class by swapping in a fake EntryProvider instance.<br />

So, to recap the requirements for dependency injection:<br />

1. Don’t create class instances in other classes (if they are dependencies) — pass them into the<br />

class from outside.<br />

2. Don’t type-hint concrete classes — create interfaces.<br />

“When you go and get things out of the refrigerator for yourself, you can cause problems.<br />

You might leave the door open, you might get something Mommy or Daddy doesn’t<br />

want you to have. You might even be looking for something we don’t even have or<br />

which has expired.<br />

What you should be doing is stating a need, ‘I need something to drink with lunch,’ and<br />

then we will make sure you have something when you sit down to eat.”<br />

— John Munsch<br />

You can learn more about Dependency Injection, from Taylor’s book, at: https://leanpub.com/laravel.<br />

.<br />

Inversion Of Control<br />

Inversion of Control (IoC) is the name given to the process that involves assembling class instances<br />

(and the resolution of class instances in general) within a container or registry. Where the registry<br />

pattern involves defining class instances and then storing them in some global container; IoC

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!