如何在 Symfony2 项目中配置扩展 PersistentObject 的 Doctrine2 实体?
我希望能够使用这里描述的 PersistentObject http://www.doctrine-project.org/blog/a-doctrine-orm-odm-base-class.html 在 Symfony2 项目开发期间,避免创建和删除 getter 和在数据库和实体设计不断变化的同时,setter 无休止地进行.
I would like to be able to use the PersistentObject described here http://www.doctrine-project.org/blog/a-doctrine-orm-odm-base-class.html during development of a Symfony2 project, to avoid creating and deleting getters and setters endlessly whilst the database and entity design are in flux.
如简要文档(下面的代码引用)中所建议的那样,在 Symfony2 项目中的何处配置"ObjectManager?它应该在控制器中吗?如果是,它会是什么样子?
Where in a Symfony2 project does one 'configure' the ObjectManager, as suggested in the brief documentation (code quote below)? Should it be in the controller, and if so, what would it look like?
$entityManager = EntityManager::create(...);
PersistentObject::setObjectManager($entityManager);
我找不到任何工作示例(尽管我确实在 stackoverflow 上找到了 Zend2 框架的类似示例:在 Zend 框架中使用来自 Doctrine 的 PersistentObject
I cannot find any working examples (although I did find this parallels example for the Zend2 framework on stackoverflow: Using PersistentObject from Doctrine in Zend Framework
感谢您的时间!
推荐答案
PersistentObject 是一个不需要手动持久化的对象.因此,它使用 php 的 __call()
方法提供了神奇的 getter 和 setter.
The PersistentObject is an object which you don't manually have to persist. It thereby provides magic getters and setters using php's __call()
method.
您只需在实体类中扩展对象并在控制器中使用它.无需生成 getter 和 setter.
You simply extend the Object in your entity class and use it inside your controller. without the need to generate getters and setters.
示例实体
<?php
namespace VendorYourBundleYourEntity;
use DoctrineCommonPersistencePersistentObject;
use DoctrineCommonPersistenceObjectManager;
use DoctrineORMMapping as ORM;
class YourEntity extends PersistentObject
{
// i added the constructor in order to save the setObjectManager()
// call in the the controller
public function __construct(ObjectManager $om)
{
$this->setObjectManager($om);
}
/**
* @ORMId
* @ORMColumn(type="integer")
* @ORMGeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORMColumn(type="string", length=100)
*/
protected $name;
// ... more properties
}
示例控制器操作
class YourController extends Controller
{
public function yourAction($name)
{
$em = $this->get('doctrine')->getManager('default');
$entity = new YourEntity($em); // __construct calls setObjectManager($em)
$entity->setName($name); // magic setter is used here
// ... no need for $em->persist($entity);
$em->flush(); // $entity is being persisted.
}
// ...
您可以使用 ...
$em = $this->get('doctrine')->getManager(); // gets default manager
$em = $this->get('doctrine')->getManager('default'); // same as above
$em = $this->getDoctrine()->getManager(); // using alias
相关文章