How to create an Illuminate / Support / Facade / App facade for a standalone Illuminate IoC Container

In my standalone (without Laravel) project, I want to use the Illuminate IoC container. I would also like to access the application container through the App facade provided by the illuminate/support component. I installed both components (v5.0.28). Here is my (simplified) code:

 function setup_App(){ $container = new Illuminate\Container\Container(); Illuminate\Support\Facades\Facade::setFacadeApplication($container); class_alias('Illuminate\Support\Facades\App', 'App'); } setup_App(); App::bind('w', 'Widget'); $widget = App::make('w'); 

Unfortunately, trying to link something leads to:

 Fatal error: Call to undefined method Illuminate\Support\Facades\App::bind() in ...\illuminate\support\Facades\Facade.php on line 213 

Here is the code on this line

 $instance = static::getFacadeRoot(); ... return $instance->$method($args[0], $args[1]); // <--- line 213 

Where $instance is an instance of Illuminate\Support\Facades\App , $method == 'bind' , $args[0] == 'w' and $args[1] == 'Widget' . The problem is that $instance not an instance of Illuminate\Container\Container , and the class Illuminate\Support\Facades\App does not have support for calling arbitrary functions by its static property $app .

To do this, I added the following function to the Illuminate\Support\Facades\App :

 public function __call( $method , array $arguments ) { return call_user_func_array(array(static::$app, $method), $arguments); } 

But, of course, editing an external component is not what you need to do !!! Surely someone has come across this before!

So the question is: what is the right way to do this?

+5
source share
1 answer

You are missing one key component. The Application class must be bound to the container. The facade is looking for a class associated with the "application", but nothing happens, therefore, your mistake. You can fix the problem by binding the Illuminate\Container\Container class to the 'app':

 function setup_App(){ $container = new Illuminate\Container\Container(); Illuminate\Support\Facades\Facade::setFacadeApplication($container); $container->singleton('app', 'Illuminate\Container\Container'); class_alias('Illuminate\Support\Facades\App', 'App'); } setup_App(); App::bind('w', 'Widget'); 
+1
source

All Articles