<?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();
});
}
}
<?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');
}