我使用symfony 2.3和php doctrine 2.
该计划有以下型号:
AND MAIN CLASS BadOrderList - 错误订单列表,此类代码:
private $factory;
private $repository;
private $manager;
public function __construct(
BadOrderEntryFactory $f,
BadOrderEntryRepository $r,
BadOrderEntryManager $m
) {
$this->factory = $f;
$this->repository = $r;
$this->manager = $m;
}
public function has(Order $order)
{
return $this->repository->existsByOrder($order);
}
public function add(Order $order)
{
if (! $this->has($order)) {
$entry = $this->factory->create($order);
$this->manager->save($entry);
}
}
public function remove(Order $order)
{
$entry = $this->repository->findOneByOrder($order);
if ($entry !== null) {
$this->manager->delete($entry);
}
}
我非常喜欢这门课程的设计。我想了很多。 一切都很美好。但!有一个问题:必须在事务中执行方法添加和删除操作。
PHP Docrine 2中的事务代码如下所示:
<?php
$em->getConnection()->beginTransaction();
try {
//... do some work
$em->getConnection()->commit();
} catch (Exception $e) {
$em->getConnection()->rollback();
throw $e;
}
但是如何在BadOrderList中调用此代码?
我花了很多时间并根据数据库(相应的PHP Doctrine 2)删除了,并再次创建它? 现在依赖项隐藏在BadOrderEntryRepository和BadOrderEntryManager类中。
如何在类BadOrderList中隐藏对事务机制的依赖?
答案 0 :(得分:4)
在我们讨论之后,我会回答你的问题。 问题实际上不是&#34;如何隐藏类BadOrderList中对事务机制的依赖?&#34; ,但如何将模型与持久层分离?(在特定情况下为Doctrine2)。
我尝试用一些代码说明我的建议
class BadOrderEntry
// Bad - is too bad word to describe an order here. Why is it bad? Is it Declined? Cancelled?
{
private $order;
// some code
}
class BadOrderEntryFactory
{
// If there is not to much processing to build BadOrderEntry better use factory method like BadOrderEntry::fromOrder($order);
}
class BadOrderEntryRepository
{
// here is some read model
}
class BadOrderEntryManager
// ITS a part of our model and shouldn't be coupled to ORM
{
public function save(BadEntry $be)
{
// some model events, model actions
$this->doSave($be); // here we should hide our storage manipulation
}
protected function doSave($be) // it can be abstract, but may contain some basic storage actions
{
}
// similar code for delete/remove and other model code
}
class ORMBadOrderEntryManager extends BadOrderEntryManager
// IT'S NOT the part of your model. There is no business logic. There is only persistent logic and transaction manipulation
{
protected $entityManager;
// some constructor to inject doctrine entitymanager
protected doSave($be)
{
$em = $this->entityManager;
$em->getConnection()->beginTransaction(); // suspend auto-commit
try {
$em->persist($be);
$em->flush();
$em->getConnection()->commit();
} catch (Exception $e) {
$em->getConnection()->rollback();
throw $e;
}
}
}
// You can also implement ODMBadOrderEntryManager, MemcacheBadOrderEntryManager etc.
因此,如果我们谈论目录结构,您的所有模型都可以移出捆绑并在任何地方使用。你的Bundle结构就像:
BadEntryBundle
|
+ Entity
| |
| --- BadOrderEntryEntity.php
|
+ ORM
| |
| --- ORMBadOrderEntryManager.php
然后您只需将ORMBadOrderEntryManager注入BadOrderEntryList
答案 1 :(得分:1)
您可以将您的类转换为服务,并在您的类中注入服务容器之后将其调用。 您可以在此处找到有关dependency injection的更多信息:
$injectedContainerOfService->get("id_of_your_service")