To adapt your service provider so that it can be used both with an authenticated user and in a cron task, you need to modify the logic to handle cases where there is no authenticated user. In a cron job, you typically won't have an authenticated user, so you'll need to pass the company information directly.
Here's how you can modify your service provider to accommodate both scenarios:
- Modify the Service Provider: Update the
registermethod to accept a company parameter when no user is authenticated.
public function register(): void
{
$this->app->singleton(DatasourceInterface::class, function (Application $app, $params = []) {
$user = $this->app->make('auth')->user();
$company = $params['company'] ?? ($user ? $user->company : null);
if (!$company) {
throw new Exception('No company available', 404);
}
$datasource = $company->datasource?->value;
$credentials = $company->datasource_credentials;
if ($datasource) {
switch ($datasource) {
case 'pipedrive':
return new PipedriveDataService($this->app->make('config')->get('services.pipedrive.api_url'), $credentials);
case 'googlesheet':
return new GoogleSheetDataService($this->app->make('config')->get('services.googlesheet.api_url'), $credentials);
default:
throw new Exception('Unsupported data source', 404);
}
}
});
}
- Using the Service Provider in a Cron Task: When running a cron task, you can pass the company information directly to the service provider.
foreach ($companies as $company) {
$dataservice = app(DatasourceInterface::class, ['company' => $company]);
// Use $dataservice as needed
}
Explanation:
-
Service Provider Modification: The service provider now accepts an optional
companyparameter. If a user is authenticated, it defaults to using the user's company. If not, it uses the company passed in the parameters. -
Cron Task Usage: When iterating over companies in a cron task, you pass each company to the service provider using Laravel's
app()helper, which allows you to resolve the service with additional parameters.
This approach ensures that your service provider can be used both in a web context with an authenticated user and in a background job or cron task where you manually specify the company.