1. Go to this page and download the library: Download suvera/winter-doctrine library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
#[Autowired]
private EntityManager $defaultEm;
public function findUser(int $id): ?User {
// Always fresh data. Always isolated from other requests.
return $this->defaultEm->find(User::class, $id);
}
// WRONG: this repository dies with the first request's notebook.
private EntityRepository $userRepo;
// RIGHT: ask the EntityManager every time.
$this->defaultEm->getRepository(User::class)->find($id);
use dev\winterframework\coroutine\CoroutineRunner;
while (true) {
// Each batch runs with a fresh notebook, then throws it away.
CoroutineRunner::runInFreshCoroutine(fn() => $this->processNextBatch());
}
t
#[Autowired("admindb-doctrine-em")]
private EntityManager $adminEm;
#[Transactional(transactionManager: "admindb-doctrine-emtxn")]
public function executeInTransaction(): void {
// do something here
foreach ($objects as $obj) {
$this->adminEm->persist($obj);
}
// do more things here
}
t
use dev\winterframework\doctrine\orm\EmTransactionManager;
use dev\winterframework\stereotype\Autowired;
use dev\winterframework\stereotype\Service;
use dev\winterframework\txn\support\DefaultTransactionDefinition;
use dev\winterframework\util\log\Wlf4p;
use Doctrine\ORM\EntityManager;
#[Service]
class UserService {
use Wlf4p;
#[Autowired]
private EmTransactionManager $txnManager;
private function getEm(): EntityManager {
return $this->txnManager->getEntityManager();
}
public function createUser(User $user): User
{
$status = $this->txnManager->getTransaction(new DefaultTransactionDefinition());
try {
$this->getEm()->persist($user);
$this->getEm()->flush();
$this->txnManager->commit($status);
return $user;
} catch (\Throwable $e) {
$this->txnManager->rollback($status);
throw $e;
}
}
public function updateUser(User $user): User
{
$status = $this->txnManager->getTransaction(new DefaultTransactionDefinition());
try {
$existing = $this->getEm()->find(User::class, $user->getId());
if ($existing) {
$existing->setName($user->getName());
$existing->setEmail($user->getEmail());
$existing->setAge($user->getAge());
$this->getEm()->flush();
}
$this->txnManager->commit($status);
return $user;
} catch (\Throwable $e) {
$this->txnManager->rollback($status);
throw $e;
}
}
public function deleteUser(int $id): bool
{
$status = $this->txnManager->getTransaction(new DefaultTransactionDefinition());
try {
$user = $this->getEm()->find(User::class, $id);
if ($user) {
$this->getEm()->remove($user);
$this->getEm()->flush();
$this->txnManager->commit($status);
return true;
}
$this->txnManager->commit($status);
return false;
} catch (\Throwable $e) {
$this->txnManager->rollback($status);
throw $e;
}
}
public function findById(int $id): ?User
{
return $this->getEm()->find(User::class, $id);
}
public function findAll(): array
{
return $this->getEm()->getRepository(User::class)->findAll();
}
public function findByEmail(string $email): ?User
{
return $this->getEm()->getRepository(User::class)->findOneBy(['email' => $email]);
}
}
t
use dev\winterframework\doctrine\dbal\DbalTransactionManager;
use dev\winterframework\stereotype\Autowired;
use dev\winterframework\stereotype\Service;
use dev\winterframework\txn\support\DefaultTransactionDefinition;
use dev\winterframework\util\log\Wlf4p;
use Doctrine\DBAL\Connection;
#[Service]
class UserDbalService {
use Wlf4p;
#[Autowired("defaultdb-doctrine-dbal")]
private Connection $conn;
#[Autowired("defaultdb-doctrine-dbaltxn")]
private DbalTransactionManager $txnManager;
public function createUser(User $user): User
{
$status = $this->txnManager->getTransaction(new DefaultTransactionDefinition());
try {
$this->conn->executeStatement(
"INSERT INTO doctrine_users (name, email, age) VALUES (:name, :email, :age)",
['name' => $user->getName(), 'email' => $user->getEmail(), 'age' => $user->getAge()]
);
$user->setId((int) $this->conn->lastInsertId());
$this->txnManager->commit($status);
return $user;
} catch (\Throwable $e) {
$this->txnManager->rollback($status);
throw $e;
}
}
public function updateUser(User $user): User
{
$status = $this->txnManager->getTransaction(new DefaultTransactionDefinition());
try {
$this->conn->executeStatement(
"UPDATE doctrine_users SET name = :name, email = :email, age = :age WHERE id = :id",
['name' => $user->getName(), 'email' => $user->getEmail(), 'age' => $user->getAge(), 'id' => $user->getId()]
);
$this->txnManager->commit($status);
return $user;
} catch (\Throwable $e) {
$this->txnManager->rollback($status);
throw $e;
}
}
public function deleteUser(int $id): bool
{
$status = $this->txnManager->getTransaction(new DefaultTransactionDefinition());
try {
$affected = $this->conn->executeStatement(
"DELETE FROM doctrine_users WHERE id = :id",
['id' => $id]
);
$this->txnManager->commit($status);
return $affected > 0;
} catch (\Throwable $e) {
$this->txnManager->rollback($status);
throw $e;
}
}
public function findById(int $id): ?User
{
$row = $this->conn->fetchAssociative(
"SELECT * FROM doctrine_users WHERE id = :id",
['id' => $id]
);
if (!$row) return null;
return new User((int) $row['id'], $row['name'], $row['email'], isset($row['age']) ? (int) $row['age'] : null);
}
public function findAll(): array
{
$rows = $this->conn->fetchAllAssociative("SELECT * FROM doctrine_users ORDER BY id");
$users = [];
foreach ($rows as $row) {
$users[] = new User((int) $row['id'], $row['name'], $row['email'], isset($row['age']) ? (int) $row['age'] : null);
}
return $users;
}
public function findByEmail(string $email): ?User
{
$row = $this->conn->fetchAssociative(
"SELECT * FROM doctrine_users WHERE email = :email",
['email' => $email]
);
if (!$row) return null;
return new User((int) $row['id'], $row['name'], $row['email'], isset($row['age']) ? (int) $row['age'] : null);
}
}
use dev\winterframework\doctrine\lock\DbalLockManager;
use dev\winterframework\stereotype\Autowired;
use dev\winterframework\stereotype\Bean;
use dev\winterframework\stereotype\Configuration;
use dev\winterframework\util\concurrent\LockManager;
use Doctrine\DBAL\Connection;
#[Configuration]
class LockConfig {
#[Autowired("admindb-doctrine-dbal")]
private Connection $adminDbal;
#[Bean('dbLockManager')]
public function dbLockManager(): LockManager {
return new DbalLockManager($this->adminDbal);
}
}
#[Lockable(name: 'order-#{id}', ttlSeconds: 30, waitMilliSecs: 2000, lockManager: 'dbLockManager')]
public function settle(int $id): void { /* runs on one pod at a time per order */ }
namespace App\Config;
use dev\winterframework\pdbc\datasource\DataSourceConfig;
use dev\winterframework\pdbc\multitenant\TenantDataSourceProvider;
use dev\winterframework\stereotype\Autowired;
use dev\winterframework\stereotype\Component;
use Doctrine\ORM\EntityManager;
#[Component]
class MyTenantDataSourceProvider implements TenantDataSourceProvider {
#[Autowired("admindb-doctrine-em")]
private EntityManager $adminEm;
public function getTenantDataSourceConfig(string $tenantId): DataSourceConfig {
// Query your admin database (or any config store) for this tenant
// $tenant = $this->adminEm->find(Tenant::class, $tenantId);
$config = new DataSourceConfig();
$config->setName($tenantId);
$config->setUrl("mysql:host=localhost;port=3306;dbname=tenant_{$tenantId}_db");
$config->setUsername("tenant_user");
$config->setPassword("tenant_pass");
return $config;
}
public function getAllTenantIds(): array {
// Return every known tenant id (used for batch operations)
return [];
}
}
use dev\winterframework\stereotype\Autowired;
use dev\winterframework\stereotype\Service;
use dev\winterframework\doctrine\multitenancy\MultiTenantManager;
#[Service]
class TenantOrderService {
#[Autowired]
private MultiTenantManager $mt;
public function createOrder(string $tenantId, array $orderData): void {
// Get tenant-specific EntityManager
$em = $this->mt->getEntityManager($tenantId);
// Get tenant-specific Connection
$conn = $this->mt->getConnection($tenantId);
// Get tenant-specific TransactionManager
$txnMgr = $this->mt->getEmTransactionManager($tenantId);
$em->persist($order);
$em->flush();
}
public function processOrders(string $tenantId): void {
$em = $this->mt->getEntityManager($tenantId);
$em->getConnection()->beginTransaction();
try {
// ... do work ...
$em->getConnection()->commit();
} catch (\Throwable $e) {
$em->getConnection()->rollBack();
throw $e;
}
}
}
#[Component]
class CrossTenantService {
#[Autowired("regionDb-manager")]
private MultiTenantManager $regionMt;
#[Autowired("productDb-manager")]
private MultiTenantManager $productMt;
public function process(string $regionTenantId, string $productTenantId): void {
$regionEm = $this->regionMt->getEntityManager($regionTenantId);
$productConn = $this->productMt->getConnection($productTenantId);
// ...
}
}
// Close all cached connections and entity managers
$this->mt->close();
// Evict a specific tenant (force reconnect on next access)
$this->mt->evictTenant('tenant-123');
// List all currently-cached tenant IDs
$tenantIds = $this->mt->getCachedTenantIds();
// Get the tenant data source provider for advanced use
$provider = $this->mt->getTenantDataSourceProvider();
final class TenantFilter extends SQLFilter implements ParameterizedFilter {
public static function currentParameters(): array {
return ['tenant' => TenantContext::currentId()]; // null when there is no tenant
}
public function addFilterConstraint(ClassMetadata $meta, string $alias): string {
if (!$meta->hasField('tenantId')) {
return '';
}
if ($this->getParameter('tenant') === "''") {
return '1 = 0'; // no tenant: match nothing (fail closed)
}
return $alias . '.' . $meta->getColumnName('tenantId') . ' = ' . $this->getParameter('tenant');
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.