What is the basic difference between Factory and Abstract Factory in ZF2
Factory is used to create a single service per context. Abstract Factory is used to create many similar services per context. For instance, imagine that your application requires a single repository "UsersRepository" which connects to your database and allows you to fetch data from "Users" table. You would create a factory for this service as following:
class UsersRepositoryFactory implements FactoryInterface
{
public createService(ServiceLocatorInterface $serviceLocator)
{
return new \MyApp\Repository\UsersRepository();
}
}
However, in real world, you may want to interact with many tables in your application, therefore you should consider to utilize Abstract Factory to create repository services for each table.
class RepositoryAbstractFactory implements AbstractFactoryInterface
{
canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
return class_exists('\MyApp\Repository\'.$requestedName);
}
createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$class = '\MyApp\Repository\'.$requestedName;
return new $class();
}
}
As you can see, you don't have to create a separate factory for each repository service in your application.