#### 應用場景
例如 `手機短信服務` 我們經常在很多地方需要調用這個模塊,我們應該怎么做才好呢?推薦將該模塊提升為系統級別的服務:
> 1 在AppServiceProvider.php的文件底部,添加以下代碼:
~~~
/**
* 短信服務
*/
private function registerSMS()
{
$this->app->singleton('sms', function($app)
{
$config = config('sms');
$accountsid = array_get($config, 'account_sid');
$token = array_get($config, 'token');
return new SMS(compact('accountsid', 'token'), array_get($config, 'app_id'));
});
}
~~~
> 2 在AppServiceProvider.php的register()函數中,添加以下代碼:
~~~
public function register()
{
...
$this->registerSMS();
...
}
~~~
> 3 創建 app/Services/SMS.php
~~~
<?php
namespace App\Services;
class SMS {
public function send()
{
return ...;
}
}
~~~
使用方式:
~~~
app('sms')->send();
~~~