Laravel ServiceContainer and Facade (beginner)

时间:2015-05-04 19:27:40

标签: php laravel inversion-of-control

Firs time using the IOC and Facades. I'm trying to make a "teamleader" facade so that I can call

Teamleader::getCompaniesByCountry(); 

And I'm getting the error

Non-static method Notflip\Teamleader\Teamleader::getCompaniesByCountry() should not be called statically, assuming $this from incompatible context

This is my ServiceProvider

<?php namespace Notflip\Teamleader;

use Illuminate\Support\ServiceProvider;

class TeamleaderServiceProvider extends ServiceProvider {


    public function register()
    {
        $this->app['teamleader'] = $this->app->bind('teamleader', function($app){
            return new Teamleader();
        });
    }

    public function boot()
    {
        //
    }
}

And this is my Facade

<?php namespace Notflip\Teamleader\Facades;

use Illuminate\Support\Facades\Facade;

class Teamleader extends Facade {

    protected static function getFacadeAccessor() { return 'teamleader'; }

}

1 个答案:

答案 0 :(得分:3)

You need to call methods on the facade instead of the actual class. So if your class is Notflip\Teamleader\Teamleader and your facade is Notflip\Teamleader\Facades\Teamleader then you essentially need to call Notflip\Teamleader\Facades\Teamleader::getCompaniesByCountry().

Obviously you don't want to do that. So you add an alias in your config/app.php file. Under the 'Aliases' array you could add:

'TeamLeader' => 'Notflip\Teamleader\Facades\Teamleader'

Then you can just call \Teamleader::getCompaniesByCountry()

In addition, you may need to change you service provider to this:

$this->app->bind('teamleader', function($app){
    return new Teamleader();
});

Instead of this:

$this->app['teamleader'] = $this->app->bind('teamleader', function($app){
    return new Teamleader();
});