krak / doctrine-util
Doctrine 工具
v0.1.1
2018-04-17 05:02 UTC
Requires (Dev)
- peridot-php/peridot: ^1.18
- symfony/var-dumper: ^3.2
This package is auto-updated.
Last update: 2024-09-10 00:11:54 UTC
README
持有一些通用的函数/类,这些函数/类在处理 Doctrine ORM 时非常有用。
安装
使用 composer 在 krak/doctrine-util
下安装。
使用方法
<?php use function Krak\DoctrineUtil\{repoChunk, repoUntilEmpty}; $q = $em->createQuery('SELECT u FROM User u'); repoChunk($q, 100, function($users) { foreach ($users as $user) { // do something with user } }); $q = $em->createQuery('SELECT u FROM User u WHERE u.email_sent = false'); repoUntilEmpty($q, 100, function($users) { foreach ($users as $user) { sendEmail($user); $user->setEmailSent(true); } }, 1000); // run 1000 max
实体仓库
Krak\DoctrineUtil\EntityRepository
包含一些令人惊叹的功能,使得与 doctrine 实体仓库一起工作更加容易。
// extend the DoctrineUtil Entity Repository class UserRepository extends Krak\DoctrineUtil\EntityRepository { } // or set the default in the entity manager config $em->getConfiguration()->setDefaultRepositoryClassName(Krak\DoctrineUtil\EntityRepository::class);
您可以使用以下方式与您的仓库交互
$userRepo = $em->getRepository(User::class); // `get` alias for finding the entity or throw if not found try { $user = $userRepo->get($id); } catch (Doctrine\ORM\EntityNotFoundException $e) { } // Simple fluent interface // find users where ids are in 1,2, and 3 $users = $userRepo->where(['id' => [1,2,3]])->find(); // retrieve a single user with the state and address entities loaded. $user = $userRepo->with(['state', 'address'])->get(1);
API
/** Chunks the result into arrays. After each chunk the em is flushed, then cleared */
integer repoChunk(AbstractQuery $query, integer $chunk_size, callable $handler)
/** Works exactly like repoChunk, except that it will keep chunking results until the query returns an empty result set.
This function expects that the handler will be modifying the entities so that they will no longer be in the query result */
integer repoUntilEmpty(AbstractQuery $query, integer $chunk_size, callable $handler, integer $max = INF)