Symfony3 Doctrine2 CURD

在Symfony中调用EntityManger->flush()时,默认会开启一个事务,如果不想要开启事务,可以参考以下的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 取得用户持久类
$userRepository = $this->getEntityManager()->getRepository('CommonBundle:User');
// 获取用户
$user = $userRepository->find(1);
// 更新数据
$updateData = ['nickname' => 'test'];
// 插入数据
$insertData = ['nickname' => 'xxxx'];

// 第一种方式:saveUser1 方法, 使用 EntityManager [flush] 来更新或插入(persist), 每次更新或插入会开启事务
// 更新
$updateUser = $userRepository->saveUser1($user, $updateData);
// 插入
$insertUser = $userRepository->saveUser1('User', $insertData);

// 第二种方式:saveUser2 方法, 使用 EntityManager [update,insert] 来更新或插入, 每次更新或插入不会开启事务
// 更新
$updateUser = $userRepository->saveUser2($user, $updateData);
// 插入
$insertUser = $userRepository->saveUser2('User', $insertData);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# Bundles\CommonBundle\Entity\UserRepository
<?php

namespace Bundles\CommonBundle\EntityRepository;

use Doctrine\ORM\EntityRepository;

/**
* UserRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class UserRepository extends EntityRepository
{
const ENTITY_NAMESPACE = 'Bundles\CommonBundle\Entity\\';

/**
* 保存用户信息
*
* @param \Bundles\CommonBundle\Entity\User $user
* @param array $data
*
* @return \Bundles\CommonBundle\Entity\User|bool
* @throws \Exception
*/
public function saveUser1($user, $data)
{
$user = $this->getEntityInstance($user, $data);
$em = $this->getEntityManager();
try {
$em->persist($user);
$em->flush();
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
return false;
}

return $user;
}

/**
* 保存用户信息
*
* @param \Bundles\CommonBundle\Entity\User $user
* @param array $data
*
* @return \Bundles\CommonBundle\Entity\User|bool
* @throws \Exception
*/
public function saveUser2($entity, $data)
{
try {
// 更新
if (is_object($entity) && $entity->getId()) {
$query = $this->createQueryBuilder('e')
->where("e.id = :eId")
->setParameter('eId', $entity->getId());
foreach ($data as $key => $val) {
$query->set("e.{$key}", ":{$key}")->setParameter($key, $val);
};
$query->update()->getQuery()->execute();
$entity = $this->getEntityInstance($entity, $data);

return $entity;
}

// 插入
$em = $this->getEntityManager();
$entity = $this->getEntityInstance($entity, $data);
$class = $em->getClassMetadata(get_class($entity));
$query = $em->getConnection()->createQueryBuilder();
foreach ($data as $key => $val) {
if ($val instanceof \DateTime) {
$val = $val->format('Y-m-d H:i:s');
}

$query->setValue("{$class->columnNames[$key]}", ":{$key}")->setParameter($key, $val);
};
$result = $query->insert($class->getTableName())->execute();
if ($result) {
$data['id'] = $class->idGenerator->generate($em, $entity);
$entity = $em->getUnitOfWork()->createEntity($class->name, $data);

return $entity;
}
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}

return false;
}

/**
* 取得初始化数据后的实例
*
* @param string|object $entity 实例对象或命名空间
* @param array $initData 初始化数据
*
* @return object
* @throws
*/
public function getEntityInstance($entity, $initData = [])
{
if (is_string($entity)) {
$entity = self::ENTITY_NAMESPACE . $entity;
$instance = new $entity();
} else {
$instance = $entity;
}

$reflectionClass = new \ReflectionClass($entity);

foreach ($initData as $key => $value) {
if ($reflectionClass->hasProperty($key)) {
$methodName = 'set' . ucfirst($key);
if ($reflectionClass->hasMethod($methodName)) {
$instance->$methodName($value);
}
}
}

return $instance;
}
}

更新或插入,可以使用以下方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php

namespace Bundles\CommonBundle\EntityRepository;

use Doctrine\ORM\EntityRepository;

class AbstractRepository extends EntityRepository
{
/**
* 保存实体
*
* @param array $data
* @param object|string $entity
*
* $userRepository = $this->EntityManager()->getRepository('User');
* // 插入
* $user = $userRepository->saveEntity(['nickname' => 'test']);
* // 更新
* $user = $userRepository->findOneById(1);
* $user = $userRepository->saveEntity(['nickname' => 'testabc'], $user);
* // 取得初始化数据后的实体
* $user = $userRepository->getEntityInstance('User', ['nickname' => 'hello']);
*
* @return false|object
* @throws \Exception
*/
public function saveEntity($data, $entity = null)
{
try {
$isInsert = is_object($entity) ? false : true;
$em = $this->getEntityManager();
$entity = $this->getEntityInstance($entity, $data);
$isInsert && $em->persist($entity);
$em->flush();
} catch (\Exception $e) {
return false;
}

return $entity;
}

/**
* 取得初始化数据后的实例
*
* @param object|string $entity 实例对象或实体名称
* @param array $initData 初始化数据
*
* @return object
* @throws
*/
public function getEntityInstance($entity, $initData = [])
{
if (is_object($entity)) {
$instance = $entity;
} else {
$classMetadata = $this->getClassMetadata();
$entity = is_string($entity) ? "{$classMetadata->namespace}\\{$entity}" : $classMetadata->getName();
$instance = new $entity();
}

$reflectionClass = new \ReflectionClass($entity);
foreach ($initData as $key => $value) {
if ($reflectionClass->hasProperty($key)) {
$methodName = 'set' . ucfirst($key);
if ($reflectionClass->hasMethod($methodName)) {
$instance->$methodName($value);
}
}
}

return $instance;
}
}
0%