doctrine create an entity dynamically

2019-04-11 07:07发布

Is there a way to create and modify entities and tables in a db dynamically (from a php script)?

For example, I want to generate an entity from an array:

fields{
    id: integer,
    name: string,
    ... and so on
}

And than generate a table in the bd

I know only one simple solution: to create yml or xml file and run a console command from my script, or use DBAL

1条回答
你好瞎i
2楼-- · 2019-04-11 07:36

I know only one simple solution: to create yml or xml file and run a console command from my script, or use DBAL

You can also generate an entity from command line, for example:

$ php app/console generate:doctrine:entity --no-interaction \
    --entity=AcmeBlogBundle:Post \
    --fields="id:integer title:string(100) body:text" \
    --format=xml

This uses the SensioGeneratorBundle, that is defined only in dev and test environments.

So, it is a little bit hacky but you'll need to call this command with the right environment:

$ php app/console generate:doctrine:entity […] --env=dev

The Process component can be used in order to launch this command.

So you may end up with something like this:

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$command = 'php app/console generate:doctrine:entity --no-interaction '.
    '--entity=AcmeBlogBundle:Post '.
    '--fields="id:integer title:string(100) body:text" '.
    '--format=xml';

$process = new Process($command);
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();
查看更多
登录 后发表回答