You know that in Symfony2 a new entity can be defined as in the following example:
use Acme\StoreBundle\Entity\Product;
public function defaultController() {
$product = new Product();
$product->setName('Pippo');
$product->setPrice(19.99);
....
// Use Doctrine EntityManager to store the Product object
}
Suppose that you know that the Product class has the following namespace: "AcmeHomeBundle:Product". It would by nice to create the $product object by using the namespace (e.g. by using the EntityManager or something similar).
public function defaultController() {
$item = createObjectFromNamespace("AcmeHomeBundle:Product");
$item->setName('Pippo');
$item->setPrice(19.99);
....
// Use Doctrine EntityManager to store the Item object
}
Do you know if this is possible?
Suppose that you have a string that provides the entity type
You should do this...
$entityInfo = $this->em->getClassMetadata("entityNameSpace:entityName");
$entityMember = $entityInfo->newInstance();
If you wanna use a setter method by string:
$entitySetMethod = "set".\ucfirst("entityDataMemberName");
\call_user_func(array($entityMember, $entitySetMethod), $parameter);
If you really want to, you can do this:
$product = new Acme\JournalBundle\Entity\Product();
$article = new Acme\JournalBundle\Entity\Article();
But you'd have to type it out every time you wanted to create a new entity in that namespace. If you simply used a use statement at the top of you class:
use Acme\JournalBundle\Entity\Product,
Acme\JournalBundle\Entity\Article;
You could then create new articles and products with a simple:
$product = new Product();
$article = new Article();
They do the same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With