Laravel 5 BindingResolutionException in Container.php line 827

Error:

laravel-ioc-binding-exception
laravel-ioc-binding-exception

Context that caused this eror

test controller
test controller
foo service with php primitive type
foo service with php primitive type

When working with laravel 5, have you ever ask yourself that how Laravel IOC work, how Laravel IOC can handle concrete class binding instead of defining in somewhere (for laravel in Service providers).

Basically, if you inject a concrete class to another class, it will automatically bind to that class by laravel Container

Overview of Laravel Container (make, build, getDependencies, resolveClass (or nonClass))

Screenshot from 2016-03-14 09:38:57

 

 

 

 

 

laravel 5 container class:
make function
build function
getDependencies function

By default, If you inject a concrete class to another class, its will automatically bind and resolve by Laravel container.

Service Container Laravel The PHP Framework For Web Artisans
Service Container Laravel The PHP Framework For Web Artisans
laravel ioc build class based on concrete class name
laravel ioc build class based on concrete class name

but, in case in the constructor of some class you inject to a string or non-class parameter, how laravel 5 handle this  https://github.com/laravel/framework/blob/5.2/src/Illuminate/Container/Container.php#L793

laravle-container-getDependencies
laravle-container-getDependencies

Its not acceptable that throw an error if a non-class cannot resolveable, but its not make sense to make a function name resolveNonClass just only throw an error (imo, should handle this 😉

There is many ways to deal with this is that writing an service provider to inject a string to another class like this (basically, a service provider abstract class contains $app instance, just bind a dependency manually into it). This is one way

then register above service provider to config/app.php
 

its works!!!, other way to bypass this, is use Str provider class instead of built in string primitive php type.

foo service with Str class
foo service with Str class

By the way, need to update Laravel Container class to deal with primitive type ??? in this function resolveNonClass https://github.com/laravel/framework/blob/5.2/src/Illuminate/Container/Container.php#L823

laravel fw container resolveNonClass
laravel fw container resolveNonClass

Reference:
https://laravel.com/docs/5.1/container
https://github.com/laravel/framework/blob/5.2/src/Illuminate/Container/Container.php
http://culttt.com/2014/03/24/exploring-laravels-ioc-container/
http://php.net/manual/en/class.reflectionclass.php