Você está na página 1de 18

O que um ORM pode fazer

por você?
Conhecendo o Doctrine.
Índice:

1. Introdução
2. Camadas
3. Modelos
4. Schema
5. DQL
6. Listeners
7. Validação
8. Behaviors Internos
9. Fixtures
10. CLI (Command Line Interface)
11. Migrations
12. Futuro
Introdução

1. O que é ORM (Mapeamento Objecto-Relacional)?


○ Mapeamento objecto-relacional (ou ORM) é uma técnica de
desenvolvimento utilizada para reduzir a impedância da programação
orientada aos objetos utilizando bancos de dados relacionais. As tabelas
do banco de dados são representadas através de classes
e os registros de cada tabela são representados como instâncias das
classes correspondentes. http://pt.wikipedia.org/wiki/Orm
2. Vantagens e desvantagens
3. Onde utilizar?
Camadas

1. Banco de Dados
○ fbsql, ibase, mssql, mysql, mysqli, oci, pgsql, querysim e
sqlite.
2. Abstração
○ PHP Data Objects (PDO) http://br.php.net/pdo
3. Doctrine DBAL (Database Abstraction Layer)
4. ORM
Modelos
<?php

/**
* This class has been auto-generated by the Doctrine ORM Framework
*/
abstract class BaseNoticia extends sfDoctrineRecord
{
public function setTableDefinition()
{
$this->setTableName('noticia');
$this->hasColumn('id', 'integer', 4, array('type' => 'integer'...
$this->hasColumn('usuario_id', 'integer', 4, array('type'...
$this->hasColumn('titulo', 'string', 255, array('type' =>...
$this->hasColumn('texto', 'string', 2147483647, array('type'...
}

public function setUp()


{
$this->hasOne('Usuario', array('local' => 'usuario_id',
'foreign' => 'id'));
}
}
Schema

Endereco:
tableName: endereco
columns:
id:
type: integer(4)
unsigned: 1
primary: true
autoincrement: true
...

Noticia:
tableName: noticia
columns:
id:
type: integer(4)
unsigned: 1
...
relations:
Usuario:
local: usuario_id
foreign: id
type: one
DQL

<?php

// test.php

// ...
$q = Doctrine_Query::create()
->select('u.username, p.*')
->from('User u')
->leftJoin('u.Phonenumbers p')

echo $q->getSql();
Listeners
<?php

class BlogPost extends Doctrine_Record


{
public function setTableDefinition()
{
$this->hasColumn('title', 'string', 200);
$this->hasColumn('content', 'string');
$this->hasColumn('created', 'date');
$this->hasColumn('updated', 'date');
}

public function preInsert($event)


{
$this->created = date('Y-m-d', time());
}

public function preUpdate($event)


{
$this->updated = date('Y-m-d', time());
}
}
Validação
<?php

// models/User.php

class User extends BaseUser


{
// ...

public function setTableDefinition()


{
parent::setTableDefinition();

// ...

$this->hasColumn('username', 'string', 255, array(


'notnull' => true,
'primary' => true,
)
);
}
}
Behaviors Internos

1. Versionable
2. Timestampable
3. Sluggable
4. I18n
5. NestedSet
6. Searchable
7. Geographical
8. SoftDelete
Behaviors Internos
<?php

// models/BlogPost.php

class BlogPost extends Doctrine_Record


{
public function setTableDefinition()
{
$this->hasColumn('title', 'string', 255);
$this->hasColumn('body', 'clob');
}

public function setUp()


{
$this->actAs('Versionable', array(
'versionColumn' => 'version',
'className' => '%CLASS%Version',
'auditLog' => true,
'deleteVersions' => true
)
);
}
}
Behaviors Internos
// test.php

// ...
$sql = Doctrine::generateSqlFromArray(array('BlogPost'));
echo $sql[0] . "\n";
echo $sql[1];

/* echo
CREATE TABLE blog_post_version (id BIGINT,
title VARCHAR(255),
body LONGTEXT,
version BIGINT,
PRIMARY KEY(id,
version)) ENGINE = INNODB
CREATE TABLE blog_post (id BIGINT AUTO_INCREMENT,
title VARCHAR(255),
body LONGTEXT,
version BIGINT,
PRIMARY KEY(id)) ENGINE = INNODB
ALTER TABLE blog_post_version ADD FOREIGN KEY (id) REFERENCES
blog_post(id) ON UPDATE CASCADE ON DELETE CASCADE */
Behaviors Internos

$blogPost = new BlogPost();


$blogPost->title = 'Test blog post';
$blogPost->body = 'test';
$blogPost->save();

$blogPost->title = 'Modified blog post title';


$blogPost->save();

print_r($blogPost->toArray());

/* print
Array
(
[id] => 1
[title] => Modified blog post title
[body] => test
[version] => 2
)
*/
Fixtures

---
# fixtures/data.yml

Resource:
Resource_1:
name: Doctrine Video Tutorial
Type: Video
Tags: [tutorial, doctrine, help]
Resource_2:
name: Doctrine Cheat Sheet
Type: Image
Tags: [tutorial, cheat, help]

ResourceType:
Video:
name: Video
Image:
name: Image

Tag:
tutorial:
...
CLI (Command Line Interface)

$ ./doctrine
Doctrine Command Line Interface

./doctrine build-all
./doctrine build-all-load
./doctrine build-all-reload
./doctrine compile
./doctrine create-db
./doctrine create-tables
./doctrine dql
./doctrine drop-db
./doctrine dump-data
./doctrine generate-migration
./doctrine generate-migrations-db
./doctrine generate-migrations-models
./doctrine generate-models-db
./doctrine generate-models-yaml
./doctrine generate-sql
./doctrine generate-yaml-db
./doctrine generate-yaml-models
./doctrine load-data
./doctrine migrate
Migrations

<?php

// migrations/1_add_table.php

class AddTable extends Doctrine_Migration_Base


{
public function up()
{
$this->createTable('migration_test', array('field1' => array(
'type' => 'string'
)));
}

public function down()


{
$this->dropTable('migration_test');
}
}
Futuro

1. Extensões
2. Plugins
3. Extensão PHP
4. Performance
Referências:

1. http://www.doctrine-project.org/ - Site oficial


2. http://pt.wikipedia.org/wiki/Orm - Wikipedia
3. http://blog.bisna.com/ - Blog de Guilherme Blanco

Você também pode gostar