41

Laravel创建服务器提供者实例

 5 years ago
source link: http://blog.hellopython.wang/laravel-serviceprovider/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

下面我们演示下如何创建服务器提供者,它是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');  
    }

其结果也是一样的。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK