app()global helper. If you do not have it enabled, you can use the
Helpersclass. For example:
functions.phpyou'll find the following code:
$appvariable becomes your reference to the container.
get(), for example:
get, all the dependencies required by it's
__construct()function will be automatically resolved from the container using type hinting.
makemethod, and pass them as a second param.
bind(). In this example,
valueis bound to the container under
commentfrom the container, the same
Commentobject is returned. This is important, as it means state is maintained automatically.
Commentobject is never created as nothing is trying to resolve
commentfrom the container.
$commentB->authorthrows an error. This is because closures will always create a new instance.
$commentBwill now be the same object as
$commentA, and we won't get any errors.
Commentclass), you can use the class name when binding:
singleton(), the same class instance is always resolved, and therefore its state is maintained.
chargemethod that accepts an
$amount. Lets add a Stripe implementation of the interface:
PaymentGateway. This is because our application doesn't care which implementation to use, it just wants to be able to charge people. We can tell the container to resolve
StripePaymentGatewaywhenever we ask for
PaymentGateway, like so:
MyClassclass in a controller's constructor and the container will resolve it for you automatically: