Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my standalone (without Laravel) project i want to use Illuminate IoC container. Also i would like to access the app container through App facade provided by 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 bind something results in:

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 that 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 is not an instance of Illuminate\Container\Container and class Illuminate\Support\Facades\App does not have any support for calling arbitrary functions on its static property $app.

To make it work i added the following function to Illuminate\Support\Facades\App:

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

But surely editing external component is not the right thing to do!!! Surely someone have encountered this before!

So the question is : What is the proper way to do this?

like image 366
Konstantin Avatar asked May 05 '15 12:05

Konstantin


1 Answers

You are missing one key component. The Application class needs to be bound to the container. The Facade is looking for a class to be bound to 'app' but nothing is, hence your error. You can fix the problem by binding the Illuminate\Container\Container class to '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');
like image 71
Patrick Stephan Avatar answered Nov 11 '22 01:11

Patrick Stephan