我应该为 Laravel 中的服务创建单独的提供程序吗?
Should I create separate provider for service in Laravel?
我在Laravel有定制服务:
<?php
namespace App\Library\Services;
class RegisterCustomerService
{
public function do()
{
return 'Output from DemoOne';
}
}
在哪些情况下我应该为此服务创建提供者,什么时候不需要?
我可以使用 RegisterCustomerService
作为特定 class 的组合,例如:
$c = new RegisterCustomerService();
或者我有义务创建提供商吗?
仅当服务需要自定义配置时才需要服务提供商。您可以在构造函数中键入任何 class,Laravel 将尝试将其解析为一个实例。
使用配置值配置服务的示例服务提供商如下所示:
class MyServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(MyCustomService::class, function ($app) {
return new MyCustomService(config('api_token'));
});
}
}
用法:
class ProjectController {
// Receives the service configured by the service provider above.
public function __construct(MyCustomService $service){
$this->service = $service;
}
}
有关服务提供商的更多详细信息:https://laravel.com/docs/5.8/providers
我在Laravel有定制服务:
<?php
namespace App\Library\Services;
class RegisterCustomerService
{
public function do()
{
return 'Output from DemoOne';
}
}
在哪些情况下我应该为此服务创建提供者,什么时候不需要?
我可以使用 RegisterCustomerService
作为特定 class 的组合,例如:
$c = new RegisterCustomerService();
或者我有义务创建提供商吗?
仅当服务需要自定义配置时才需要服务提供商。您可以在构造函数中键入任何 class,Laravel 将尝试将其解析为一个实例。
使用配置值配置服务的示例服务提供商如下所示:
class MyServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(MyCustomService::class, function ($app) {
return new MyCustomService(config('api_token'));
});
}
}
用法:
class ProjectController {
// Receives the service configured by the service provider above.
public function __construct(MyCustomService $service){
$this->service = $service;
}
}
有关服务提供商的更多详细信息:https://laravel.com/docs/5.8/providers