SlideShare a Scribd company logo
1 of 22
Download to read offline
El Modelo - Doctrine
Realizada por:
Christian Aquino |@cj_aquino
Diego Ramirez |@thedarsideofit
Para: Hydras C&S |@hydras_cs
Basada en Libro Symfony 2 en español Nacho Pacheco y The Book
Conectándonos a la BD
# app/config/parameters.yml
parameters:
database_driver: pdo_mysql
database_host: localhost
database_name:
proyecto_de_prueba
database_user:
nombre_de_usuario
database_password: password# app/config/config.yml
doctrine:
dbal:
driver: "%
database_driver%"
host: "%database_host%"
dbname: "%
database_name%"
php app/console doctrine:
database:create
Creando nuestra primer Entidad
//
src/Acme/StoreBundle/Entity/Produ
ct.php
namespace
AcmeStoreBundleEntity;
class Product
{
protected $name;
protected $price;
protected $description;
}
php app/console doctrine:generate:entity --entity="AcmeStoreBundle:
Product" --fields="name:string(255) price:float description:text"
Podemos
interactuar
con la consola de
symfony o pasar
todo en una línea
Agregando datos de mapeo a
nuestra entidad - Annotations
//
src/Acme/StoreBundle/Entity/Product.
php
namespace AcmeStoreBundleEntity;
use DoctrineORMMapping as ORM;
/**
* @ORMEntity
* @ORMTable(name="product")
*/
class Product
{
/**
* @ORMId
* @ORMColumn(type="integer")
* @ORMGeneratedValue
(strategy="AUTO")
*/
/**
* @ORMColumn(type="
string", length=100)
*/
protected $name;
/**
* @ORMColumn(type="
decimal", scale=2)
*/
protected $price;
/**
* @ORMColumn(type="text")
*/
protected $description;
}
Agregando datos de mapeo a
nuestra entidad - YAML
# src/Acme/StoreBundle/Resources/config/doctrine/Product.
orm.yml
AcmeStoreBundleEntityProduct:
type: entity
table: product
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
name:
type: string
length: 100
price:
type: decimal
scale: 2
description:
Agregando datos de mapeo a
nuestra entidad - XML
<!-- src/Acme/StoreBundle/Resources/config/doctrine/Product.
orm.xml -->
<doctrine-mapping xmlns="http://doctrine-project.
org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.
org/schemas/orm/doctrine-mapping
http://doctrine-project.org/schemas/orm/doctrine-
mapping.xsd">
<entity name="AcmeStoreBundleEntityProduct" table="
product">
<id name="id" type="integer" column="id">
<generator strategy="AUTO" />
</id>
<field name="name" column="name" type="string"
length="100" />
Generando getters y setters
Podemos crear para todo el bundle o para
varios bundles
php app/console doctrine:generate:entities
Acme/StoreBundle/Entity/Product
php app/console doctrine:generate:entities AcmeStoreBundle
php app/console doctrine:generate:entities Acme
Aplicando cambios a nuestro
esquema
Si queremos ver el sql que genera el comando
$ php app/console doctrine:schema:update --force --dump-sql
$ php app/console doctrine:schema:update --force
Persistiendo Nuestras Entidades
// src/Acme/StoreBundle/Controller/DefaultController.php
// ...
use AcmeStoreBundleEntityProduct;
use SymfonyComponentHttpFoundationResponse;
public function createAction()
{
$product = new Product();
$product->setName('A Foo Bar');
$product->setPrice('19.99');
$product->setDescription('Lorem ipsum dolor');
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return new Response('Created product id '.$product->getId());
}
Recuperando información
public function showAction($id)
{
$product = $this->getDoctrine()->getEntityManager()
->getRepository('AcmeStoreBundle:Product')
->find($id);
if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
// ... haz algo, como pasar el objeto $product a una plantilla
}
Recuperando información
// consulta por la clave principal (generalmente 'id')
$product = $repository->find($id);
// nombres dinámicos de métodos para buscar un valor basad en
columna
$product = $repository->findOneById($id);
$product = $repository->findOneByName('foo');
// recupera TODOS los productos
$products = $repository->findAll();
// busca un grupo de productos basándose en el valor de una
columna arbitraria
$products = $repository->findByPrice(19.99);
// consulta por un producto que coincide en nombre y precio
$product = $repository->findOneBy(array('name' => 'foo', 'price' =>
19.99));
// pregunta por todos los productos en que coincide el nombre, ordenados
por precio
$product = $repository->findBy( array('name' => 'foo'), array('price',
Eliminando un objeto
Consultando con DQL
$em->remove($product);
$em->flush();
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery(
'SELECT p FROM AcmeStoreBundle:Product p WHERE p.price > :price
ORDER BY p.price ASC'
)->setParameter('price', '19.99');
$products = $query->getResult();
Usando el Query Builder
$repository = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product');
$query = $repository->createQueryBuilder('p')
->where('p.price > :price')
->setParameter('price', '19.99')
->orderBy('p.price', 'ASC')
->getQuery();
$products = $query->getResult();
Agregando un Repositorio -
Annotations
// src/Acme/StoreBundle/Entity/Product.php
namespace AcmeStoreBundleEntity;
use DoctrineORMMapping as ORM;
/**
* @ORMEntity(repositoryClass="
AcmeStoreBundleEntityProductRepository")
*/
class Product
{
//...
}
Agregando un Repositorio
YAML
XML
# src/Acme/StoreBundle/Resources/config/doctrine/Product.orm.yml
AcmeStoreBundleEntityProduct:
type: entity
repositoryClass: AcmeStoreBundleEntityProductRepository
# ...
<!-- src/Acme/StoreBundle/Resources/config/doctrine/Product.orm.xml --
>
<!-- ... -->
<doctrine-mapping>
<entity name="AcmeStoreBundleEntityProduct"
repository-class="AcmeStoreBundleEntityProductRepository">
<!-- ... -->
</entity>
Métodos Propios en el Repositorio
// src/Acme/StoreBundle/Entity/ProductRepository.php
namespace AcmeStoreBundleEntity;
use DoctrineORMEntityRepository;
class ProductRepository extends EntityRepository
{
public function findAllOrderedByName()
{
return $this->getEntityManager()
->createQuery('SELECT p FROM AcmeStoreBundle:
Product p ORDER BY p.name ASC')
->getResult();
}
}
Relaciones de Entidades OneToMany
// src/Acme/StoreBundle/Entity/Category.php
// ...
use DoctrineCommonCollectionsArrayCollection;
class Category
{
// ...
/**
* @ORMOneToMany(targetEntity="Product", mappedBy="category")
*/
protected $products;
public function __construct()
{
$this->products = new ArrayCollection();
}
}
Relaciones de Entidades ManyToOne
// src/Acme/StoreBundle/Entity/Product.php
// ...
class Product
{
// ...
/**
* @ORMManyToOne(targetEntity="Category", inversedBy="
products")
* @ORMJoinColumn(name="category_id",
referencedColumnName="id")
*/
protected $category;
}
Esquema general de la relación
Guardando objetos relacionados
use AcmeStoreBundleEntityCategory;
use AcmeStoreBundleEntityProduct;
use SymfonyComponentHttpFoundationResponse;
class DefaultController extends Controller
{
public function createProductAction()
{
$category = new Category();
$category->setName('Main Products');
$product = new Product();
$product->setName('Foo');
$product->setPrice(19.99);
// relaciona este producto a la categoría
$product->setCategory($category);
$em = $this->getDoctrine()->getManager();
$em->persist($category);
$em->persist($product);
$em->flush();
...
Recuperando Objetos relacionados
public function showAction($id)
{
$product = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product')
->find($id);
$categoryName = $product->getCategory()->getName();
// ...
}
public function showProductAction($id)
{
$category = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Category')
->find($id);
$products = $category->getProducts();
// ...
}
Evitando el lazy loading -JOINS
// src/Acme/StoreBundle/Entity/ProductRepository.php
public function findOneByIdJoinedToCategory($id)
{
$query = $this->getEntityManager()
->createQuery('
SELECT p, c FROM AcmeStoreBundle:Product p
JOIN p.category c
WHERE p.id = :id'
)->setParameter('id', $id);
try {
return $query->getSingleResult();
} catch (DoctrineORMNoResultException $e) {
return null;
}
}

More Related Content

What's hot

jQuery for designers
jQuery for designersjQuery for designers
jQuery for designers
Johan Ronsse
 
Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0
zfconfua
 
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
Johannes Hoppe
 
Meteor로 만드는 modern web application
Meteor로 만드는 modern web applicationMeteor로 만드는 modern web application
Meteor로 만드는 modern web application
Jaeho Lee
 
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
Darwin Durand
 

What's hot (20)

Як досвід компанії перетворився на фреймворк
Як досвід компанії перетворився на фреймворкЯк досвід компанії перетворився на фреймворк
Як досвід компанії перетворився на фреймворк
 
from new class and dependency injection to PSR-11 and Auto-wiring
from new class and dependency injection to PSR-11 and Auto-wiringfrom new class and dependency injection to PSR-11 and Auto-wiring
from new class and dependency injection to PSR-11 and Auto-wiring
 
jQuery for designers
jQuery for designersjQuery for designers
jQuery for designers
 
Wek14 mysql 2
Wek14 mysql 2Wek14 mysql 2
Wek14 mysql 2
 
Gestire l'asincronia in javascript uno sguardo al futuro!
Gestire l'asincronia in javascript  uno sguardo al futuro!Gestire l'asincronia in javascript  uno sguardo al futuro!
Gestire l'asincronia in javascript uno sguardo al futuro!
 
Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0
 
Javascript per applicazioni complesse - Lo Stretto digitale
Javascript per applicazioni complesse - Lo Stretto digitaleJavascript per applicazioni complesse - Lo Stretto digitale
Javascript per applicazioni complesse - Lo Stretto digitale
 
Jquery Introduction Hebrew
Jquery Introduction HebrewJquery Introduction Hebrew
Jquery Introduction Hebrew
 
Phpex3
Phpex3Phpex3
Phpex3
 
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
 
RxSwift 예제로 감잡기
RxSwift 예제로 감잡기RxSwift 예제로 감잡기
RxSwift 예제로 감잡기
 
Symfony2でMongoDBと仲良くする方法
Symfony2でMongoDBと仲良くする方法Symfony2でMongoDBと仲良くする方法
Symfony2でMongoDBと仲良くする方法
 
Dart != JavaScript
Dart != JavaScriptDart != JavaScript
Dart != JavaScript
 
Mantto con vb2010
Mantto con vb2010Mantto con vb2010
Mantto con vb2010
 
Belajar menggunakan Api raja ongkir php
Belajar menggunakan Api raja ongkir php Belajar menggunakan Api raja ongkir php
Belajar menggunakan Api raja ongkir php
 
Java script.trend(spec)
Java script.trend(spec)Java script.trend(spec)
Java script.trend(spec)
 
Dart und JavaScript
Dart und JavaScriptDart und JavaScript
Dart und JavaScript
 
Meteor로 만드는 modern web application
Meteor로 만드는 modern web applicationMeteor로 만드는 modern web application
Meteor로 만드는 modern web application
 
Introduction to Service Worker
Introduction to Service WorkerIntroduction to Service Worker
Introduction to Service Worker
 
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
 

More from hydras_cs (15)

Clase 15 FOS
Clase 15 FOSClase 15 FOS
Clase 15 FOS
 
Clase 15
Clase 15Clase 15
Clase 15
 
Clase 14 bundles útiles
Clase 14 bundles útilesClase 14 bundles útiles
Clase 14 bundles útiles
 
Clase 13 seguridad
Clase 13   seguridad Clase 13   seguridad
Clase 13 seguridad
 
Clase 11 continuamos con formularios
Clase 11   continuamos con formulariosClase 11   continuamos con formularios
Clase 11 continuamos con formularios
 
Clase 10 validacion
Clase 10   validacionClase 10   validacion
Clase 10 validacion
 
Clase 10 formularios
Clase 10   formulariosClase 10   formularios
Clase 10 formularios
 
Clase 14 doctrine - subir archivos
Clase 14   doctrine - subir archivosClase 14   doctrine - subir archivos
Clase 14 doctrine - subir archivos
 
Clase 6 twig
Clase 6 twigClase 6 twig
Clase 6 twig
 
Clase 5 controller
Clase 5 controllerClase 5 controller
Clase 5 controller
 
Clase 4 routing
Clase 4 routingClase 4 routing
Clase 4 routing
 
Clase 3 instalación y primeros pasos
Clase 3 instalación y primeros pasosClase 3 instalación y primeros pasos
Clase 3 instalación y primeros pasos
 
Sensio labsdesktop
Sensio labsdesktopSensio labsdesktop
Sensio labsdesktop
 
Clase 2 conceptos fundamentales
Clase 2   conceptos fundamentalesClase 2   conceptos fundamentales
Clase 2 conceptos fundamentales
 
Clase 1 introducción a symfony 2
Clase 1   introducción a symfony 2Clase 1   introducción a symfony 2
Clase 1 introducción a symfony 2
 

Clase 7 el modelo

  • 1. El Modelo - Doctrine Realizada por: Christian Aquino |@cj_aquino Diego Ramirez |@thedarsideofit Para: Hydras C&S |@hydras_cs Basada en Libro Symfony 2 en español Nacho Pacheco y The Book
  • 2. Conectándonos a la BD # app/config/parameters.yml parameters: database_driver: pdo_mysql database_host: localhost database_name: proyecto_de_prueba database_user: nombre_de_usuario database_password: password# app/config/config.yml doctrine: dbal: driver: "% database_driver%" host: "%database_host%" dbname: "% database_name%" php app/console doctrine: database:create
  • 3. Creando nuestra primer Entidad // src/Acme/StoreBundle/Entity/Produ ct.php namespace AcmeStoreBundleEntity; class Product { protected $name; protected $price; protected $description; } php app/console doctrine:generate:entity --entity="AcmeStoreBundle: Product" --fields="name:string(255) price:float description:text" Podemos interactuar con la consola de symfony o pasar todo en una línea
  • 4. Agregando datos de mapeo a nuestra entidad - Annotations // src/Acme/StoreBundle/Entity/Product. php namespace AcmeStoreBundleEntity; use DoctrineORMMapping as ORM; /** * @ORMEntity * @ORMTable(name="product") */ class Product { /** * @ORMId * @ORMColumn(type="integer") * @ORMGeneratedValue (strategy="AUTO") */ /** * @ORMColumn(type=" string", length=100) */ protected $name; /** * @ORMColumn(type=" decimal", scale=2) */ protected $price; /** * @ORMColumn(type="text") */ protected $description; }
  • 5. Agregando datos de mapeo a nuestra entidad - YAML # src/Acme/StoreBundle/Resources/config/doctrine/Product. orm.yml AcmeStoreBundleEntityProduct: type: entity table: product id: id: type: integer generator: { strategy: AUTO } fields: name: type: string length: 100 price: type: decimal scale: 2 description:
  • 6. Agregando datos de mapeo a nuestra entidad - XML <!-- src/Acme/StoreBundle/Resources/config/doctrine/Product. orm.xml --> <doctrine-mapping xmlns="http://doctrine-project. org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project. org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine- mapping.xsd"> <entity name="AcmeStoreBundleEntityProduct" table=" product"> <id name="id" type="integer" column="id"> <generator strategy="AUTO" /> </id> <field name="name" column="name" type="string" length="100" />
  • 7. Generando getters y setters Podemos crear para todo el bundle o para varios bundles php app/console doctrine:generate:entities Acme/StoreBundle/Entity/Product php app/console doctrine:generate:entities AcmeStoreBundle php app/console doctrine:generate:entities Acme
  • 8. Aplicando cambios a nuestro esquema Si queremos ver el sql que genera el comando $ php app/console doctrine:schema:update --force --dump-sql $ php app/console doctrine:schema:update --force
  • 9. Persistiendo Nuestras Entidades // src/Acme/StoreBundle/Controller/DefaultController.php // ... use AcmeStoreBundleEntityProduct; use SymfonyComponentHttpFoundationResponse; public function createAction() { $product = new Product(); $product->setName('A Foo Bar'); $product->setPrice('19.99'); $product->setDescription('Lorem ipsum dolor'); $em = $this->getDoctrine()->getManager(); $em->persist($product); $em->flush(); return new Response('Created product id '.$product->getId()); }
  • 10. Recuperando información public function showAction($id) { $product = $this->getDoctrine()->getEntityManager() ->getRepository('AcmeStoreBundle:Product') ->find($id); if (!$product) { throw $this->createNotFoundException( 'No product found for id '.$id ); } // ... haz algo, como pasar el objeto $product a una plantilla }
  • 11. Recuperando información // consulta por la clave principal (generalmente 'id') $product = $repository->find($id); // nombres dinámicos de métodos para buscar un valor basad en columna $product = $repository->findOneById($id); $product = $repository->findOneByName('foo'); // recupera TODOS los productos $products = $repository->findAll(); // busca un grupo de productos basándose en el valor de una columna arbitraria $products = $repository->findByPrice(19.99); // consulta por un producto que coincide en nombre y precio $product = $repository->findOneBy(array('name' => 'foo', 'price' => 19.99)); // pregunta por todos los productos en que coincide el nombre, ordenados por precio $product = $repository->findBy( array('name' => 'foo'), array('price',
  • 12. Eliminando un objeto Consultando con DQL $em->remove($product); $em->flush(); $em = $this->getDoctrine()->getEntityManager(); $query = $em->createQuery( 'SELECT p FROM AcmeStoreBundle:Product p WHERE p.price > :price ORDER BY p.price ASC' )->setParameter('price', '19.99'); $products = $query->getResult();
  • 13. Usando el Query Builder $repository = $this->getDoctrine() ->getRepository('AcmeStoreBundle:Product'); $query = $repository->createQueryBuilder('p') ->where('p.price > :price') ->setParameter('price', '19.99') ->orderBy('p.price', 'ASC') ->getQuery(); $products = $query->getResult();
  • 14. Agregando un Repositorio - Annotations // src/Acme/StoreBundle/Entity/Product.php namespace AcmeStoreBundleEntity; use DoctrineORMMapping as ORM; /** * @ORMEntity(repositoryClass=" AcmeStoreBundleEntityProductRepository") */ class Product { //... }
  • 15. Agregando un Repositorio YAML XML # src/Acme/StoreBundle/Resources/config/doctrine/Product.orm.yml AcmeStoreBundleEntityProduct: type: entity repositoryClass: AcmeStoreBundleEntityProductRepository # ... <!-- src/Acme/StoreBundle/Resources/config/doctrine/Product.orm.xml -- > <!-- ... --> <doctrine-mapping> <entity name="AcmeStoreBundleEntityProduct" repository-class="AcmeStoreBundleEntityProductRepository"> <!-- ... --> </entity>
  • 16. Métodos Propios en el Repositorio // src/Acme/StoreBundle/Entity/ProductRepository.php namespace AcmeStoreBundleEntity; use DoctrineORMEntityRepository; class ProductRepository extends EntityRepository { public function findAllOrderedByName() { return $this->getEntityManager() ->createQuery('SELECT p FROM AcmeStoreBundle: Product p ORDER BY p.name ASC') ->getResult(); } }
  • 17. Relaciones de Entidades OneToMany // src/Acme/StoreBundle/Entity/Category.php // ... use DoctrineCommonCollectionsArrayCollection; class Category { // ... /** * @ORMOneToMany(targetEntity="Product", mappedBy="category") */ protected $products; public function __construct() { $this->products = new ArrayCollection(); } }
  • 18. Relaciones de Entidades ManyToOne // src/Acme/StoreBundle/Entity/Product.php // ... class Product { // ... /** * @ORMManyToOne(targetEntity="Category", inversedBy=" products") * @ORMJoinColumn(name="category_id", referencedColumnName="id") */ protected $category; }
  • 19. Esquema general de la relación
  • 20. Guardando objetos relacionados use AcmeStoreBundleEntityCategory; use AcmeStoreBundleEntityProduct; use SymfonyComponentHttpFoundationResponse; class DefaultController extends Controller { public function createProductAction() { $category = new Category(); $category->setName('Main Products'); $product = new Product(); $product->setName('Foo'); $product->setPrice(19.99); // relaciona este producto a la categoría $product->setCategory($category); $em = $this->getDoctrine()->getManager(); $em->persist($category); $em->persist($product); $em->flush(); ...
  • 21. Recuperando Objetos relacionados public function showAction($id) { $product = $this->getDoctrine() ->getRepository('AcmeStoreBundle:Product') ->find($id); $categoryName = $product->getCategory()->getName(); // ... } public function showProductAction($id) { $category = $this->getDoctrine() ->getRepository('AcmeStoreBundle:Category') ->find($id); $products = $category->getProducts(); // ... }
  • 22. Evitando el lazy loading -JOINS // src/Acme/StoreBundle/Entity/ProductRepository.php public function findOneByIdJoinedToCategory($id) { $query = $this->getEntityManager() ->createQuery(' SELECT p, c FROM AcmeStoreBundle:Product p JOIN p.category c WHERE p.id = :id' )->setParameter('id', $id); try { return $query->getSingleResult(); } catch (DoctrineORMNoResultException $e) { return null; } }