$logger = $container->make(Illuminate\Log\Writer::class); // or $logger = app()->make(Illuminate\Log\Writer::class); drop instance.. Or even shorter... :
given explicit instructions from the user of how to instantiate that class. If a class has dependencies, an autowiring framework will use reflection to determine and provide its dependencies.
$dependencies = $this->getConstructorDependenciesFor($key); return new $key(... $dependencies); } } It now uses reflection to figure out the constructor dependencies.
real class instantiated to a shortcut. // Illuminate/Foundation/Application public function registerCoreContainerAliases() { $aliases = [ 'app' => [ \Illuminate\Foundation\Application::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class ], // ... ]; }
the framework (like Request, Logger, Mailer) in controllers and other user-facing code ▸ Route model binding ▸ Form Requests ▸ Relying on constructor injection more confidently in custom classes
namespace Symposium\JoindIn; // ... imports class Client { // ... class properties public function __construct(Client $guzzle, Logger $logger, Cache $cache) { // ... assign as class properties } }
the container ▸ boot: called after all registrations are complete; everything else here (registering event listeners, routes, or any other functionality) ▸ defer?: can we avoid running this service provider if certain bindings aren't requested? ▸ provides: if deferred, which bindings' requests should trigger running this service provider?
aids DI. Swap in a mock or a spy easily. // in code Route::get('whatever', function (MyService $service) { return $service->get('whatever'); }); // in test $mock = Mockery::mock('MyService'); app()->instance('MyService', $mock);
// in code Route::get('whatever', function () { return Twitter::post('here is my status!'); }); // in test $mock = Mockery::mock(MyTwitterClient::class); app()->instance('twitter', $mock);