简体   繁体   English

我应该在Laravel中为服务创建单独的提供程序吗?

[英]Should I create separate provider for service in Laravel?

I have custom service in Laravel: 我在Laravel中有自定义服务:

<?php
namespace App\Library\Services;

class RegisterCustomerService
{
    public function do()
    {
        return 'Output from DemoOne';
    }

}

In which cases I should create provider for this service, when not? 在什么情况下,我应该为此服务创建提供程序?

Could I use RegisterCustomerService as composition in specific class like: 我可以将RegisterCustomerService用作特定类的组合,例如:

$c = new RegisterCustomerService();

Or am i obligated to create Provider? 还是我有义务创建提供商?

Service providers are only necessary if the service needs custom configuration. 仅当服务需要自定义配置时,才需要服务提供商。 You can typehint any class in the constructor and Laravel will try to resolve it to an instance. 您可以在构造函数中键入任何类的提示,Laravel会尝试将其解析为实例。

An example service provider that configures a service with a config value is shown below: 下面显示了使用config值配置服务的示例服务提供程序:

class MyServiceProvider extends ServiceProvider
{
   public function register()
    {
        $this->app->singleton(MyCustomService::class, function ($app) {
            return new MyCustomService(config('api_token'));
        });
    }
}

usage: 用法:

class ProjectController {
  // Receives the service configured by the service provider above.
  public function __construct(MyCustomService $service){
    $this->service = $service;
  }
}

More details about service providers: https://laravel.com/docs/5.8/providers 有关服务提供商的更多详细信息: https : //laravel.com/docs/5.8/providers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM