對於這種情況我使用型號經理,它的意圖是與實體經營業務層ORM無關的接口。喜歡的東西:
<?php
/**
* Group entity manager
*/
class GroupManager
{
/**
* Holds the Doctrine entity manager for database interaction
* @var EntityManager
*/
protected $em;
/**
* Holds the Symfony2 event dispatcher service
* @var EventDispatcherInterface
*/
protected $dispatcher;
/**
* Entity specific repository, useful for finding entities, for example
* @var EntityRepository
*/
protected $repository;
/**
* Constructor
*
* @param EventDispatcherInterface $dispatcher
* @param EntityManager $em
* @param string $class
*/
public function __construct(EventDispatcherInterface $dispatcher, EntityManager $em)
{
$this->dispatcher = $dispatcher;
$this->em = $em;
$this->repository = $em->getRepository($class);
}
/**
* @return Group
*/
public function findGroupBy(array $criteria)
{
return $this->repository->findOneBy($criteria);
}
/**
* @return Group
*/
public function createGroup()
{
$group = new Group();
// Some initialization or creation logic
return $group;
}
/**
* Update a group object
*
* @param Group $group
* @param boolean $andFlush
*/
public function updateGroup(Group $group, $andFlush = true)
{
$this->em->persist($group);
if ($andFlush) {
$this->em->flush();
}
}
/**
* Add a user to a group
*
* @param User $user
* @param Group $group
* @return Membership
*/
public function addUserToGroup(User $user, Group $group)
{
$membership= $this->em->getRepository('GroupBundle:Membership')
->findOneBy(array(
'user' => $user->getId(),
'group' => $group->getId(),
));
if ($membership && $membership->isActive()) {
return null;
} elseif ($membership && !$membership->isActive()) {
$membership->setActive(true);
$this->em->persist($membership);
$this->em->flush();
} else {
$membership = new Membership();
$membership->setUser($user);
$membership->setGroup($group);
$this->em->persist($membership);
$this->em->flush();
}
$this->dispatcher->dispatch(
GroupEvents::USER_JOINED_GROUP, new MembershipEvent($user, $group)
);
return $membership;
}
然後將服務定義:
<service id="app.model_manager.group" class="App\GroupBundle\Entity\GroupManager">
<argument type="service" id="event_dispatcher" />
<argument type="service" id="doctrine.orm.entity_manager" />
</service>
,你可以注入記錄器,郵件,路由器,或任何其他服務,你可以需要。
看看FOSUserBundle的經理,以獲得有關如何使用它們的示例和想法。
你可能想看看http://symfony.com/doc/current/book/service_container.html – PMoubed