PersistentObject是您不必手动保留的对象。因此,它使用 php 的方法提供了神奇的 getter 和 setter 。__call()
您只需在实体类中扩展 Object 并在控制器中使用它。无需生成 getter 和 setter。
示例实体
<?php
namespace Vendor\YourBundle\YourEntity;
use Doctrine\Common\Persistence\PersistentObject;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\Mapping 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);
}
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(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.
}
// ...
您可以使用以下方法之一在 symfony 控制器中获取学说实体管理器...
$em = $this->get('doctrine')->getManager(); // gets default manager
$em = $this->get('doctrine')->getManager('default'); // same as above
$em = $this->getDoctrine()->getManager(); // using alias