我想触发一个新实体的实例化。 有人可以说是否可能,以及如何? 等待一个问题,我带来了这个解决方案,在服务中获得一个新的实体...但我发现它没有足够的优化。 这是我的代码的简化摘录,附加了一个事件" onCreate"在听众中: 这运行良好,但我必须调用一个新实体,通过一个服务。我希望我的新实体直接填充而只是做" $ entity = new entity();"
abstract class serviceBaseEntity extends serviceBaseClass {
const ENTITY_CLASS = ''; // here class of entity
protected $classname;
protected $shortname;
protected $EntityManager;
protected $ObjectManager;
public function __construct(ContainerInterface $container, RequestStack $request_stack) {
parent::__construct($container, $request_stack);
$this->EntityManager = $this->container->get('doctrine.orm.entity_manager');
$this->ObjectManager = $this->container->get('doctrine')->getManager();
$this->addEventSubscriber(new serviceAnnotations($container, $request_stack));
$this->classname = $this->calledClassname::ENTITY_CLASS;
$this->shortname = (new ReflectionClass($this->classname))->getShortName();
return $this;
}
protected function addEventSubscriber(EventSubscriber $EventSubscriber) {
$this->EntityManager->getEventManager()->addEventSubscriber($EventSubscriber);
return $this;
}
public function getNew() {
$entity = new $this->classname;
$eventArgs = new LifecycleEventArgs($entity, $this->ObjectManager);
$this->EntityManager->getEventManager()->dispatchEvent(AnnotationsBase::onCreate, $eventArgs);
return $entity;
}
答案 0 :(得分:0)
也许你可以在你的实体中使用一种工厂方法,使用私有构造函数。例如:
Class MyEntity {
private function __construct( ) {
your code
}
public static function createEntity(your params) {
do some stuff
$e=new MyEntity();
do some other stuff
return $e;
}
}