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
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();
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();
}
}
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;
}
}