Instantiate entity managers¶
Inject the factory contract¶
The recommended application dependency is EntityManagerFactoryInterface:
use App\EntityManager\UserManager;
use Small\SwooleEntityManagerBundle\Contract\EntityManagerFactoryInterface;
final class UserService
{
public function __construct(
private readonly EntityManagerFactoryInterface $entityManagerFactory,
) {
}
public function load(int $userId): \App\Entity\User
{
/** @var UserManager $userManager */
$userManager = $this->entityManagerFactory->get(UserManager::class);
/** @var \App\Entity\User $user */
$user = $userManager->findOneBy(['id' => $userId]);
return $user;
}
}
The interface alias is public for compatibility, but constructor injection is preferred over pulling services directly from the container.
Controller example¶
namespace App\Controller;
use App\EntityManager\UserManager;
use Small\SwooleEntityManagerBundle\Contract\EntityManagerFactoryInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
final class UserController
{
public function __construct(
private readonly EntityManagerFactoryInterface $entityManagerFactory,
) {
}
#[Route('/api/users/{userId}', name: 'get_user_by_id', methods: ['GET'])]
public function __invoke(int $userId): JsonResponse
{
/** @var UserManager $userManager */
$userManager = $this->entityManagerFactory->get(UserManager::class);
$user = $userManager->findOneBy(['id' => $userId]);
return new JsonResponse($user->toArray());
}
}
Cached and fresh managers¶
By default, the factory caches a manager instance:
Pass true as the second argument to request a fresh instance:
Long-running worker reset¶
The bundle's concrete entity manager factory is tagged with Symfony's kernel.reset mechanism. When Symfony resets services between worker cycles, the Core manager cache is cleared through EntityManagerFactoryInterface::reset().
You can also reset it explicitly when implementing your own long-running loop:
This prevents a manager instance cached in one logical request or job from being unintentionally reused forever in a persistent worker.