Laravel Service Container and Auto resolution

Posted in Intermediate , Laravel 3 Feb 2019

Understanding of the Laravel service container is a must for every Laravel developer. Without undertstanding it thoroughly, one can not develop good Laravel applications.

Laravel does depedency resolution by using two concepts viz. 1) service container and 2) reflection (auto resolution). For depedency resolution via service container , one needs to bind classes (like interfaces, existing object instance or class) with service container and resolve them. The whole process of binding and resolution is explained in detail in this blog

If a class is not bound in service container then Laravel resolves it via reflection (auto resolution) and it works out of the box. Laravel first checks if there is a class bound in service container if not then it falls back to reflection API to get the instance of the class , if it exists. The example of reflection API is route model binding. This laracast lesson explains it very well.

Note: Service container takes precedence over reflection API i.e. if the class is bound in service container and it exists as well then whatever is bound in service container will get resolved.