John Davidson

php - Laravel service provider choose which class to inject

0 comments
Message:


I have an API and I use sanctum API tokens as authentication.


-Let's suppose I receive a request from a user.


-Based on the user I get the user's settings from db.


-User setting "selected_class" = "foo".


How do I declare a service provider that injects the "selected_class" as implementation?



My Answer:
To achieve this, you can create a custom service provider in Laravel that dynamically selects which class to inject based on the user's settings. Here's an example of how you can do this:

1. Create a new service provider by running the following command in your terminal:
bash
php artisan make:provider SelectedClassProvider


2. In the `SelectedClassProvider` class, you can use the `App` facade to retrieve the user's settings and determine which class to inject. Here's an example implementation:

php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class SelectedClassProvider extends ServiceProvider
{
public function register()
{
$selectedClass = // Retrieve the user's selected class from the database

if ($selectedClass === 'foo') {
$this->app->bind('SelectedClassInterface', 'App\Services\FooService');
} else {
$this->app->bind('SelectedClassInterface', 'App\Services\DefaultService');
}
}
}


3. Don't forget to register your new service provider in the `config/app.php` file:

php
'providers' => [
// Other service providers
App\Providers\SelectedClassProvider::class,
],


4. Now you can inject the `SelectedClassInterface` into your controllers or other classes and Laravel will automatically resolve the correct implementation based on the user's settings:

php
use App\Services\SelectedClassInterface;

class UserController extends Controller
{
protected $selectedClass;

public function __construct(SelectedClassInterface $selectedClass)
{
$this->selectedClass = $selectedClass;
}

public function index()
{
// Use the selected class implementation
$this->selectedClass->doSomething();
}
}


By following these steps, you can create a dynamic service provider in Laravel that selects which class to inject based on the user's settings.

Rate this post

4 of 5 based on 3349 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us