当前位置:网站首页>Laravel 服务提供者实例教程 —— 创建 Service Provider 测试实例
Laravel 服务提供者实例教程 —— 创建 Service Provider 测试实例
2022-07-07 14:07:00 【全栈程序员站长】
从某种意义上说,服务提供者有点类似HTTP控制器,HTTP控制器用于为相关路由注册提供统一管理,而服务提供者用于为相关服务容器提供统一绑定场所,此外服务提供者还可以做一些初始化启动操作。Laravel的每个核心组件都对应一个服务提供者,可以这么说,服务提供者是Laravel的心脏,是Laravel的核心,核心组件类在这里完成注册、初始化以供后续调用。
既然这么重要,那么如何在自己的Laravel应用中定义和使用服务提供者呢?
1、定义服务类
有了上一节有关服务容器的讲述,理解起服务提供者来很简单。我们这里先定义一个绑定到容器的测试类TestService
,为了对类的定义加以约束,我们同时还定义一个契约接口TestContract
。
定义TestContract
如下:
<?php
namespace App\Contracts;
interface TestContract
{
public function callMe($controller);
}
定义TestService
如下:
<?php
namespace App\Services;
use App\Contracts\TestContract;
class TestService implements TestContract
{
public function callMe($controller)
{
dd('Call Me From TestServiceProvider In '.$controller);
}
}
2、创建服务提供者
接下来我们定义一个服务提供者TestServiceProvider
用于注册该类到容器。创建服务提供者可以使用如下Artisan命令:
php artisan make:provider TestServiceProvider
该命令会在app/Providers
目录下生成一个TestServiceProvider.php
文件,我们编辑该文件内容如下:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\TestService;
class TestServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
* @author LaravelAcademy.org
*/
public function register()
{
//使用singleton绑定单例
$this->app->singleton('test',function(){
return new TestService();
});
//使用bind绑定实例到接口以便依赖注入
$this->app->bind('App\Contracts\TestContract',function(){
return new TestService();
});
}
}
可以看到我们使用了两种绑定方法,更多绑定方法参考服务容器文档。
3、注册服务提供者
定义完服务提供者类后,接下来我们需要将该服务提供者注册到应用中,很简单,只需将该类追加到配置文件config/app.php
的providers
数组中即可:
'providers' => [
//其他服务提供者
App\Providers\TestServiceProvider::class,
],
4、测试服务提供者
这样我们就可以在应用中使用该服务提供者了,为了测试该服务提供者我们首先使用Artisan命令创建一个资源控制器TestController
:
php artisan make:controller TestController
然后在路由配置文件routes.php
中定义路由:
Route::resource('test','TestController');
最后去TestController
中编写测试代码:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App;
use App\Contracts\TestContract;
class TestController extends Controller
{
//依赖注入
public function __construct(TestContract $test){
$this->test = $test;
}
/**
* Display a listing of the resource.
*
* @return Response
* @author LaravelAcademy.org
*/
public function index()
{
// $test = App::make('test');
// $test->callMe('TestController');
$this->test->callMe('TestController');
}
...//其他控制器动作
}
然后我们去浏览器中访问http://laravel.app:8000/test
,分别测试使用App::make
和依赖注入解析绑定类调用callMe
方法的输出,结果一样,都是:
"Call Me From TestServiceProvider In TestController"
好了,大功告成,是不是很简单?!
此外,Laravel服务提供者还支持延迟加载,具体可参考服务提供者文档。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/113202.html原文链接:https://javaforall.cn
边栏推荐
- Summary of knowledge points of xlua hot update solution
- 保证接口数据安全的10种方案
- Mysql database basic operation DQL basic query
- What are compiled languages and interpreted languages?
- Numpy --- basic learning notes
- Please supervise the 2022 plan
- leetcode 241. Different Ways to Add Parentheses 为运算表达式设计优先级(中等)
- The inevitable trend of the intelligent development of ankerui power grid is that microcomputer protection devices are used in power systems
- Three. JS introductory learning notes 15: threejs frame animation module
- 【花雕体验】15 尝试搭建Beetle ESP32 C3之Arduino开发环境
猜你喜欢
Shandong old age Expo, 2022 China smart elderly care exhibition, smart elderly care and aging technology exhibition
Good news! Kelan sundb database and Hongshu technology privacy data protection management software complete compatibility adaptation
torch. Numel action
95.(cesium篇)cesium动态单体化-3D建筑物(楼栋)
UE4 exports the picture + text combination diagram through ucanvasrendertarget2d
Numpy --- basic learning notes
AE learning 01: AE complete project summary
Plate - forme de surveillance par étapes zabbix
Talk about the cloud deployment of local projects created by SAP IRPA studio
Unity3d click events added to 3D objects in the scene
随机推荐
three.js打造酷炫下雪效果
Three. JS introductory learning notes 11:three JS group composite object
torch. Numel action
Leetcode-231-2的幂
Is it reliable to open an account on Tongda letter with your mobile phone? Is there any potential safety hazard in such stock speculation
95. (cesium chapter) cesium dynamic monomer-3d building (building)
A wave of open source notebooks is coming
L'application à l'échelle de la normalisation mature des produits ai des compagnies maritimes, cimc, leader mondial de l'intelligence artificielle portuaire et maritime / intelligence artificielle des
Mesh merging under ue4/ue5 runtime
10 schemes to ensure interface data security
Regular expression string
Description of vs common shortcut keys
Logback logging framework third-party jar package is available for free
Dotween -- ease function
Notification uses full resolution
Bidding announcement: Panjin people's Hospital Panjin hospital database maintenance project
【花雕体验】15 尝试搭建Beetle ESP32 C3之Arduino开发环境
What about the pointer in neural network C language
How to implement backspace in shell
尤雨溪,来了!