下面我们演示下如何创建服务器提供者,它是Laravel的核心。

在 app/Contracts 目录下创建 TestContract.php 文件,其内容为:

<?php  
namespace App\Contracts;  

interface TestContract {  
    public function callMe($controller);  
}

在 app/Services 目录下创建 TestService.php 文件,其内容为:

<?php  
namespace App\Services;  
use App\Contracts\TestContract;  

class TestService implements TestContract {  
    public function callMe($controller){  
        dd("Call me from TestServiceProvider in ".$controller);  
    }  
}

在 config/app.php 文件中providers中添加内容,以便进行注册:

...  
App\Providers\RiakServiceProvider::class,

创建1个服务提供类:

php artisan make:provider RiakServiceProvider

其内容为:

<?php  

namespace App\Providers;  

use App\Services\TestService;  
use Illuminate\Support\ServiceProvider;  

class RiakServiceProvider extends ServiceProvider  
{  
    /**  
     * Bootstrap the application services.  
     *  
     * @return void  
     */  
    public function boot()  
    {  
        //  
    }  

    /**  
     * Register the application services.  
     *  
     * @return void  
     */  
    public function register()  
    {  
        $this->app->bind("App\Contracts\TestContract",function(){  
            return new TestService();  
        });  
    }  
}

在ServiceProvider中提供了2个方法,其中register方法用于注册服务,而boot用于引导服务。

在控制器IndxController中添加如下内容:

<?php  

namespace App\Http\Controllers;  

use App;  
use Illuminate\Http\Request;  
use App\Contracts\TestContract;  

class IndexController extends Controller  
{  
    public function __construct(TestContract $test){  
        $this->test = $test;  
    }  
    public function index(){  
        $this->test->callMe("IndexController");  
    }  
}

访问浏览器可以得到如下的结果:

"Call me from TestServiceProvider in IndexController"

另外,还可以使用App的make方法进行调用。

public function index(){  
        $test = App::make('test');  
        $test->callMe('IndexController');  
    }

其结果也是一样的。