KA.
KA.

Reputation: 4484

Generate Models from Mysql database

I am working on the project in which Doctrine is used. So I started learning Doctrine and write simple test and stuck at the very beginning. I have developed lot of cakePHP apps before and I have good idea about cake bake.

I have a test mysql database and 2 tables in it. I want to generate all model classes to start with and I want to include them in controllers of my MVC app to CRUD.

I installed Doctrine using composer and got a folder called /vendor inside project folder. Created a new bootstrap.php inside project folder

/vendor
/bootstrap.php 

code inside bootstrap.php is

<?php

// bootstrap.php
require_once "vendor/autoload.php";

use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;

$paths = array("/path/to/entities-or-mapping-files");
$isDevMode = false;

// the connection configuration
$dbParams = array(
    'driver' => 'pdo_mysql',
    'user' => 'root',
    'password' => '',
    'dbname' => 'test',
);

$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$em = EntityManager::create($dbParams, $config);

I see that there is a method called Doctrine_Core::generateModelsFromDb in older version.

I just want basic models to start with and want to know how to include them in other PHP files to CRUD.

Upvotes: 2

Views: 7090

Answers (1)

Juan Pablo Santos
Juan Pablo Santos

Reputation: 1220

I understand you want to generate a set of entity classes and mapping information from a database. With Doctrine you need both the entity classes and the mapping information for them. The mapping information is basically a bunch of .yml or .xml files. Both things can be generated from a database using the tools provided by Doctrine. This is usually done once at the beginning of your project. From the mapping information Doctrine can automatically generate PHP classes you can use in your code (e.g to persist entitites). The mapping information can also be added as pseudo-annotations in classes but I don't have experience with that so I won't get into that.

The command you're looking for is

php doctrine orm:convert-mapping --from-database yml /path/to/mapping-path-converted-to-yml

This assumes you have configured Doctrine to access your database already.

Once you have done this you can generate the entities with

php doctrine orm:generate-entities

This should create the classes used for CRUD operations. To use the classes you just need to include them in your code and then use an EntityManager object to operate on them.

More information on reverse engineering can be found here: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/tools.html#reverse-engineering

By the way, if you have a schema in a MySQL Workbench file there are scripts that can generate entity classes and the mapping information from it.

Upvotes: 6

Related Questions