I have a REST web service in API Tools. I’m trying to have my Resource factory implement the Laminas\ServiceManager\Factory\FactoryInterface
.
I get a message from my IDE (phpStorm) that says that the ContainerInterface->get()
could throw a couple of different Exceptions. Now, it is not likely that I will get one (unless somebody else messes up my module.config.php). Even so, I know that I should surround it with a try/catch.
Here’s my problem: I have no idea what to do if I get an Exception!
Obviously, the Resource needs my model for the web service to work.
QUESTION: Is there an “elegant” way to have this fail? Here’s my Resource factory code:
use Claims\Model\MbrClaimsModel;
use Laminas\ServiceManager\Factory\FactoryInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
class MbrClaimsDocsResourceFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null): MbrClaimsDocsResource
{
try {
$model = $container->get(MbrClaimsModel::class);
} catch (ContainerExceptionInterface |NotFoundExceptionInterface $e) {
// TODO: What???
}
return new MbrClaimsDocsResource($model);
}
}
One thought I had was to just set the $model
to null, and then when I get in my resource, the first thing I do is check to see for if (is_null($this->model)){
and return an ApiProblem. But I’d have to replicate that code every method in the resource (fetch, fetchAll, patch, delete, etc.) That doesn’t seem so elegant to me.
Can you think of a better way?