Instanciate entity managers
Entity manager factory
Entity manager factory is a service that lets you get an entity manager :
use Small\SwooleEntityManagerBundle\Contract\EntityManagerFactoryInterface;
use App\EntityManager\UserManager;
$userManager = $container->get(EntityManagerFactoryInterface::class)
->get(UserManager::class);
You can inject in an existing service or use it in a controller :
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Attribute\Route;
use Small\SwooleEntityManagerBundle\Contract\EntityManagerFactoryInterface;
use App\EntityManager\UserManager;
#[AsController]
class UserController extends AbstractController
{
#[Route('/api/get-user/{userId}', 'get_user_by_id', methods: ['GET'])]
public function getUserById($userId): JsonResponse
{
/** @var \App\Entity\User $user */
$user = $this->get(EntityManagerFactoryInterface::class)
->get(UserManager::class)
->findOneBy(['id' => $userId])
;
return new JsonResponse($user->toArray());
}
}