Kolvin
Kolvin

Reputation: 11

Programmatically load Entity in symfony

I am trying to load in Entity classes and use within a loop in order to load content in dynamically from files into relating tables.

Is there any way i can load in all Entity files from the following

use AppBundle\Entity\aaPostcode;
use AppBundle\Entity\abPostcode;
use AppBundle\Entity\acPostcode;
use AppBundle\Entity\adPostcode;

in such a way like this?

use AppBundle\Entity\*

Not sure if this is possible in Symfony.

My next issue is using the the prefixedEntity within a loop like so -

new $entityPrefix

When i am setting $entityPrefix to the following format

$entityPrefix = str_replace([".csv"], "", $entityFilename) . "Postcode" . '()';

which returns the string of

"abPostcode()"

can anyone advise as to why calling

new $entityPrefix;

is not working

Thanks in advance for any help!

trying to call

new $entityPrefix();

returns

[Symfony\Component\Debug\Exception\ClassNotFoundException]           
Attempted to load class "abPostcode" from the global namespace.      
Did you forget a "use" statement for "AppBundle\Entity\abPostcode"?  

even when i current am hrd coding the use stament to call

use AppBundle\Entity\abPostcode;

Upvotes: 0

Views: 929

Answers (3)

Robert Saylor
Robert Saylor

Reputation: 1369

I kinda ran into this issue migrating data from one database type to another. IE: Oracle to MySQL. With hundreds of tables the use section would get big.

This is on Symfony 5.2.x BTW.

When I run a query using a standard repository or a repository linked to the table I can call the entity with its full namespace.

$oracle = $em2->getRepository(\App\Entity\Oracle\Appoints::class)->Appoints();

So I did not have to load "use App\Entity\Oracle\Appoints

Then I can create a new object in the same way:

$mysqlObject = new \App\Entity\OracleAppPoints();

Upvotes: 0

Kolvin
Kolvin

Reputation: 11

I solved this by pulling out the functionality into a helper and running a switch statement based on the input - in this case a {prefix}

Upvotes: 0

Smaïne
Smaïne

Reputation: 1389

You can't instanciate dynamically your class without ginving the full namespace. Try that :

$namespace = "AppBundle\Entity\\";
$entityName = "YourEntity";
$namespace .= $entityName;
$class = new $namespace();

This is working for me...

Upvotes: 1

Related Questions