• Like
Clase 7  el modelo
Upcoming SlideShare
Loading in...5
×

Clase 7 el modelo

  • 149 views
Uploaded on

www.hydrascs.com

www.hydrascs.com

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
149
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
5
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 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; } }