Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new entity in Symfony2 with Doctrine by using the "namespace"

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

like image 371
JeanValjean Avatar asked Dec 16 '22 00:12

JeanValjean


2 Answers

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);
like image 127
eglaf Avatar answered May 12 '23 21:05

eglaf


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.

like image 37
Chris McKinnel Avatar answered May 12 '23 21:05

Chris McKinnel