Providers

Assegai providers are used to define dependencies that can be injected into other components of your application, such as controllers.

Creating providers

Providers can be created by defining a class that has been marked with the #[Injectable] attribute. This attribute tells Assegai to treat the class as a provider, allowing it to be injected into other components using constructor property promotion.

Here is an example of a provider class in Assegai:

src/Spears/SpearsService.php
use Assegai\Core\Attributes\Injectable;
use Assegai\Orm\Attributes\InjectRepository;
use Assegai\Orm\Management\Repository;

#[Injectable]
class SpearsService
{
  public function __construct(
    #[InjectRepository(SpearEntity::class)]
    private readonly Repository $spearsRepository
  )
  {
  }

  public function findAll(): array
  {
    return $this->spearsRepository->find();
  }

  public function findOne(int $id): ?SpearEntity
  {
    return $this->spearsRepository->findOne(['where' => ['id' => $id]]);
  }

  // Provider methods go here}

In this example, the SpearsService provider class has a constructor that takes in a Repository object as an argument. This Repository object is injected into the provider using the #[InjectRepository] attribute, which specifies the type of entity that the repository should manage.

The service defines two methods:

1. findAll()
This method returns an array of all the spear entities in the spears repository.
2. findOne(int $id)
This method takes an integer $id as an argument and returns a single spear entity with the given id from the Spears repository, or null if no such entity exists.

Injecting providers

Once a provider has been defined, it can be injected into other components of your application by including it as an argument in the constructor of that component. For example, here is how you might use the SpearsService provider in a controller:

src/Spears/SpearsController.php
use Assegai\App\Spears\SpearsService;
use Assegai\Core\Attributes\Controller;
use Assegai\Core\Attributes\Http\Get;

#[Controller('spears')]
class SpearsController
{
  public function __construct(private readonly SpearsService $spearsService)
  {
  }

  #[Get]
  function findAll()
  {
    return $this->spearsService->findAll();
  }

  #[Get(':id')]
  function findOne(int $id)
  {
    return $this->spearsService->findOne($id);
  }
}

In this example, the SpearsController class has a constructor that takes in a SpearsService object as an argument. This object is then available to be used within the controller's methods.

By using providers and constructor property promotion, Assegai allows you to easily manage dependencies within your application and promote code reusability.