dependent upon a specific Database object • Table is no longer loosely coupled, it's now tightly coupled to Database • Table has a responsibility to ensure Database is managed (ie how it's constructed). • How would you unit test Table::save?
• Testing Table::save requires having a mock of DB • The mock enables DB::save to pass or fail independently • Mock also prevents actually writing to the database
Table is dependent upon a specific Database object • Table is no longer loosely coupled, it's now tightly coupled to Database • Table has a responsibility to ensure Database is managed • How would you unit test Table::save?
::save with a certain signature. • Table is dependent upon being provided a specific Database instance. • Table is now loosely coupled to Database. • Table has no responsibility to Database's constructor. • Table tests can use a mocked instance of Database, for unit testing.
testing • But not exclusively to that • DI lets you design software that talks to an interface and thus abstract away details • Enables easier swapping of pieces of software • Also extremely useful for APIs
a reliable public API for a set of objects • DI means other programmers can swap out the objects in use at run time • Modern PHP Frameworks/Projects use this pattern
PayPal for Stripe becomes a single location for changes (hopefully) • Method names are the same • Method params are (hopefully) the same • Unit Tests stay the same
Pattern for solving a particular class of problem • There is no one "best" way to do DI • Most Frameworks have a Dependency Injector Container • Container is a fancy word for basically a DI framework