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

只愿长相守 提交于 2020-01-02 03:51:08

问题


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?


回答1:


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');


来源:https://stackoverflow.com/questions/30053695/how-to-create-illuminate-support-facade-app-facade-for-standalone-illuminate-ioc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!