I want to create a service class in my app that has the AuthorizationService
as a dependency so it can access the user’s identity. I have this constructor:
public function __construct(
private readonly AuthorizationServiceInterface $authorization,
private readonly OrganizationsTable $organizationsTable,
private readonly array $config = []
) { ... }
I have an AuthorizationServiceProvider
that I’ve registered in Application::services()
but it actually does two jobs:
- extends
ServiceProvider
and implementsservices()
- implements
AuthorizationServiceProviderInterface
and implementsgetAuthorizationService()
(Technically the book says to attach the latter interface to your Application class but I broke it out into a separate class and I instantiate that class and pass it to the AuthorizationMiddleware
. This part works fine.)
For my services method in this class I have:
public function services(ContainerInterface $container): void
{
$container->add(AuthorizationServiceInterface::class, function () use ($container) {
$request = $container->get(ServerRequestInterface::class);
return $this->getAuthorizationService($request);
});
}
So basically I’m trying to register the AuthorizationServiceInterface
in the container then provide a concrete implementation by calling my getAuthorizationService()
method in this same class.
Crucially, in this class I also have:
protected $provides = [
AuthorizationServiceInterface::class,
];
However, I’m getting this error:
“App\\Service\\Crud\\Organization\\OrganizationSearcher::__construct(): Argument #1 ($authorization) must be of type Authorization\\AuthorizationServiceInterface, string given”
In the past this has always indicated (to me) that I’m missing that class FQCN in the $provides
class property. But as you can see, it is there.
What am I doing wrong?
- Tried ensuring the
AuthorizationServiceInterface
was present in the$provides
class property - Tried clearing the cache with
bin/cake cache clear_all
- Tried reordering the Service Providers in
Application::services()
to see if that had any effect
Ultimately, I expect the service container to be able to resolve an AuthorizationServiceInterface
by using my getAuthorizationService()
method and pass it to my service class that needs it.