Search code examples
phplaravellaravel-4facade

Laravel Facades - Passing parameter to __construct()


If I am creating a Facade, and I want to pass parameters before it becomes instantiated, what do I do?


Solution

  • The facade's underlying service is resolved through the IoC container, so all you have to do is bind it correctly.

    Create a Service Provider, and pass in whatever you want:

    use Illuminate\Support\ServiceProvider;
    
    class FooServiceProvider extends ServiceProvider {
    
        public function register()
        {
            $this->app->bind('foo', function()
            {
                return new Foo('pass whatever you want');
            });
        }
    }
    

    Don't forget to load the service provider in your app's config array.

    Then use that bound key in your facade:

    class Bar extends Facade {
    
        protected static function getFacadeAccessor() { return 'foo'; }
    
    }