当前位置:网站首页>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
边栏推荐
- SPI master RX time out interrupt
- [wechat applet] Chapter (5): basic API interface of wechat applet
- Migration and reprint
- 10 schemes to ensure interface data security
- Three. JS introductory learning notes 18: how to export JSON files with Blender
- Strengthen real-time data management, and the British software helps the security construction of the medical insurance platform
- Shipping companies' AI products are mature, standardized and applied on a large scale. CIMC, the global leader in port and shipping AI / container AI, has built a benchmark for international shipping
- Step by step monitoring platform ZABBIX
- Aerospace Hongtu information won the bid for the database system research and development project of a unit in Urumqi
- Three singleton modes of unity (hungry man, lazy man, monobehavior)
猜你喜欢
Dotween -- ease function
Performance comparison of tidb for PostgreSQL and yugabytedb on sysbench
numpy--疫情数据分析案例
It's different for rich people to buy a house
AE learning 01: AE complete project summary
[flower carving experience] 15 try to build the Arduino development environment of beetle esp32 C3
Rongyun won the 2022 China Xinchuang digital office portal excellence product award!
模仿企业微信会议室选择
Xingruige database was shortlisted as the "typical solution for information technology application and innovation in Fujian Province in 2021"
统计学习方法——感知机
随机推荐
Numpy --- basic learning notes
Excessive dependence on subsidies, difficult collection of key customers, and how strong is the potential to reach the dream of "the first share of domestic databases"?
分类模型评价标准(performance measure)
MySQL数据库基本操作-DQL-基本查询
torch.numel作用
Limit of total fields [1000] in index has been exceeded
持续创作,还得靠它!
Multiplication in pytorch: mul (), multiply (), matmul (), mm (), MV (), dot ()
[excelexport], Excel to Lua, JSON, XML development tool
Learn good-looking custom scroll bars in 1 minute
121. 买卖股票的最佳时机
安科瑞电网智能化发展的必然趋势电力系统采用微机保护装置是
Leetcode-136-只出现一次的数(用异或来解答)
Rongyun won the 2022 China Xinchuang digital office portal excellence product award!
Three. JS introductory learning notes 19: how to import FBX static model
10 schemes to ensure interface data security
Step by step monitoring platform ZABBIX
应用程序和matlab的通信方式
喜讯!科蓝SUNDB数据库与鸿数科技隐私数据保护管理软件完成兼容性适配
Unity3D_ Class fishing project, control the distance between collision walls to adapt to different models