在我们讨论之后,我会回答你的问题.
问题实际上不是“如何隐藏类BadOrderList中对事务机制的依赖?”,而是如何将模型与持久层分离? (在特定情况下的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