I currently had a colleague reviewing my code and he had a comment on a factory class I created. It's very simple:
class ResponseFactory
{
public function create(array $curlInfo, array $rawResponse): ResponseInterface
{
return new Response($curlInfo, $rawResponse);
}
}
$responseFactory = new ResponseFactory();
$response = $responseFactory->create(...);
His comment was that I should use the __invoke()
-method of PHP. In that case, the code would look like this:
class ResponseFactory
{
public function __invoke(array $curlInfo, array $rawResponse): ResponseInterface
{
return new Response($curlInfo, $rawResponse);
}
}
$responseFactory = new ResponseFactory();
$response = $responseFactory(...);
Now I am wondering: is this just a matter of taste? Or is there real benefit in using __invoke()
over a public create()
-method?
Any thoughts or insights on this matter are more than welcome. I'm really trying to find good use cases for the __invoke()
-method, but I'm not sure if a factory is one of them.
Response
and factory parameters look too specific. If at least one of them would be factory's property then it would make more sense. Now it looks like either class that is calling the factory or some part of it should be factory itself. \$\endgroup\$