laravel5.4 服务提供者设置

  进行编辑laravel时,需要进行编辑的是App文件夹,在这里我们需要的是两个文件夹Contracts,该文件夹用于存放接口文件,Services中是服务文件,我们首先在Contracts中建立TestContract.php文件内容如下:

<?php
namespace App\Contracts;

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

在Services当中建立TestServce.php文件

<?php
namespace App\Services;

use App\Contracts\TestContract;

class TestService implements TestContract {
	public function callMe($controller)
	{
		// TODO: Implement callMe() method.
		echo "This is called by ".$controller;
	}
}

在php终端中输入 
php artisan make:provider TestServiceProvider
然后编辑 register函数

<?php

namespace App\Providers;

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

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

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
    	//绑定单例
		$this->app->singleton("test", function($app){
			return new TestService();
		});
		//使用接口进行绑定
		$this->app->bind('App\Contracts\TestContract', function(){
			return new TestService();
		});
    }
}

所以会有两种方式进行获得实例化,一个是App::make("test")获得TestService类的对象,另一种则是通过接口App\Contracts\TestContract获得TestService类的对象

这样就OK了,接下来就做的是创建一个controller

php artisan make:controller TestController

接下来看下TestController

<?php

namespace App\Http\Controllers;

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

class TestController extends Controller
{
    //

	public function __construct(TestContract $test) {
		$this->test = $test;
	}

	public function index(){
		//$test = \App::make("test");
		$this->test->callMe("test");
	}
}

这样就通过服务提供者调用了TestService!

猜你喜欢

转载自blog.csdn.net/dasgk/article/details/77666762
今日推荐