working-with-existing-databases.txt 2.24 KB
Newer Older
jepso's avatar
jepso committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
+++ Introduction

A common case when looking for ORM tools like Doctrine is that the database and the code that access it is growing large/complex. A more substantial tool is needed then manual SQL code. 

Doctrine has support for generating Doctrine_Record classes from your existing database. There is no need for you to manually write all the Doctrine_Record classes for your domain model. 

+++ Making the first import

Let's consider we have a mysql database called test with a single table called 'file'.

The file table has been created with the following sql statement:

<code type="sql">
CREATE TABLE file (
    id INT UNSIGNED AUTO_INCREMENT NOT NULL,
    name VARCHAR(150),
    size BIGINT,
    modified BIGINT,
    type VARCHAR(10),
    content TEXT,
    path TEXT,
    PRIMARY KEY(id))
</code>

Now we would like to convert it into Doctrine record class. It can be achieved easily with the following code snippet:

27
<code type="php">
jepso's avatar
jepso committed
28 29 30
require_once('lib/Doctrine.php');

spl_autoload_register(array('Doctrine', 'autoload'));
31
$conn = Doctrine_Manager::connection('mysql://root:dc34@localhost/test');
jepso's avatar
jepso committed
32 33 34

// import method takes one parameter: the import directory (the directory where
// the generated record files will be put in
35
$conn->import->importSchema('myrecords');
jepso's avatar
jepso committed
36 37 38 39
</code>

That's it! Now there should be a file called File.php in your myrecords directory. The file should look like:

40
<code type="php">
jepso's avatar
jepso committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
/**
 * This class has been auto-generated by the Doctrine ORM Framework
 * Created: Saturday 10th of February 2007 01:03:15 PM
 */
class File extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('id', 'integer', 4, array('notnull' => true,
                                                   'primary' => true,
                                                   'unsigned' > true,
                                                   'autoincrement' => true));
        $this->hasColumn('name', 'string', 150);
        $this->hasColumn('size', 'integer', 8);
        $this->hasColumn('modified', 'integer', 8);
        $this->hasColumn('type', 'string', 10);
        $this->hasColumn('content', 'string', null);
        $this->hasColumn('path', 'string', null);
    }
    public function setUp()
    {

    }
}
</code>

+++ Import options