Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are anonymous functions used in ioc containers like Pimple

I know in Pimple container, dependencies are declared as

$container = new Pimple(); 
$container['db'] = function (){
  return new SomeClass; 
}; 

My question is what if I just declared dependencies as simple arrays like this.

$container = new Pimple();
$container['db'] = new SomeClass; 

What is the difference?

like image 464
robue-a7119895 Avatar asked Dec 13 '25 08:12

robue-a7119895


1 Answers

The difference is something called lazy loading, specifically lazy initialization.

In your first example SomeClass is not actually instantiated until it is requested. In your second example it is instantiated right away. So, even if the request never hits the database the object is created and a connection is established.

By using your first example the connection to the database is never established if the request never actually uses the database.

like image 116
Charles Sprayberry Avatar answered Dec 16 '25 00:12

Charles Sprayberry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!