How to create multiple non-shared instances without injecting the ServiceLocator in ZendFramework2?

I have a factory that creates a non-shared service and a controller factory in my module.config.php file. This part of the configuration looks like this:

"service_manager" => [
    "factories" => [
        EntityUser::class => FactoryEntityUserFactory::class
    ],
    "shared" => [
        EntityUser::class => false
    ]
],
"controllers" => [
    "factories" => [
        ControllerUserAdminController::class => FactoryControllerUserAdminControllerFactory::class
    ]
]

The User entity is non-shared, because I allow the administrator to add multiple users at the same time, therefore I need to instantiate multiple instances of the User entity class.

Here is my controller factory:

<?php

namespace UserFactoryControllerCore;

use UserControllerUserAdminController;
use InteropContainerContainerInterface;
use UserEntityUser;
use ZendServiceManagerFactoryInterface;
use ZendServiceManagerServiceLocatorInterface;

class UserAdminControllerFactory implements FactoryInterface{

    /**
     * @param ContainerInterface $container
     * @param string $requestedName
     * @param array|null $options
     *
     * @return UserAdminController
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null){
        $serviceLocator = $container->getServiceLocator();

        return new UserAdminController($serviceLocator->get(User::class));
    }

    /**
     * @param  ServiceLocatorInterface $serviceLocator
     *
     * @return UserAdminController
     */
    public function createService(ServiceLocatorInterface $serviceLocator){
        return $this($serviceLocator, UserAdminController::class);
    }

}

Currently, it injects only a single instance of the User entity class inside the constructor of the controller. However, I need an undefined amount of new instances, based on what the administrator wants to do.

One possible solution is to pass the whole service locator and create new instances every time by calling $this->getServiceLocator()->get(User::class) in the controller, BUT this is considered to be an anti-pattern.

The question here is how to create new instances of the User in the controller, using the UserFactory class?


Source: stackoverflow-php