Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Symfony2 y MongoDB - deSymfony 2012

7,596 views

Published on

MongoDB es un motor de base de datos NoSQL que ha ganado mucha popularidad en los últimos tiempos, ya que ofrece muchos beneficios a la hora de desarrollar aplicaciones web.

En esta charla daremos una breve introducción a su instalación, configuración y funcionamiento. Luego repasaremos las distintas alternativas a la hora de usarlo en nuestras aplicaciones desarrolladas con PHP y Symfony2, y explicaremos cómo puede incrementar la velocidad de desarrollo y ayudar con aplicaciones web de alto rendimiento.

Published in: Technology
  • DOWNLOAD THE BOOK INTO AVAILABLE FORMAT (New Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THE can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THE is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBOOK .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, CookBOOK, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, EBOOK, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THE Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THE the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THE Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THE BOOK INTO AVAILABLE FORMAT (New Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THE can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THE is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBOOK .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, CookBOOK, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, EBOOK, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THE Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THE the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THE Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Symfony2 y MongoDB - deSymfony 2012

  1. 1. Saturday, June 16, 2012
  2. 2. Saturday, June 16, 2012
  3. 3. ¿Quién soy? ⁃ Argentino viviendo en Estados Unidos desde 1999 ⁃ Desarrollador PHP & Symfony ⁃ Fundador de la primera lista de discusión de PHP de habla hispana - Socio fundador de ServerGrove ⁃ Maestro de la parrillaSaturday, June 16, 2012
  4. 4. Saturday, June 16, 2012
  5. 5. Saturday, June 16, 2012
  6. 6. ServerGrove! ⁃ Fundada en 2005 ⁃ Proveedor de servicios de hosting especializado en PHP, Symfony, ZendFramework, y otros ⁃ Servidores en Europa y Estados Unidos ⁃ Mongohosting.com en beta!Saturday, June 16, 2012
  7. 7. La comunidad es nuestra guia ⁃ Muy activos en la comunidad de Open Source contribuyendo con código o patrocinando eventos y grupos de usuariosSaturday, June 16, 2012
  8. 8. Agenda - Introducción a MongoDB - PHP y MongoDB - Librerías en PHP - Symfony2 y MongoDBSaturday, June 16, 2012
  9. 9. ¿Qué es MongoDB? ¿Quién es 10Gen?Saturday, June 16, 2012
  10. 10. Mongo Mongo viene de "humongous". Usado para describir algo extremadamente grande o importanteSaturday, June 16, 2012
  11. 11. MongoDB es una base de datos NoSQL, escalable, de alta performance y de código abierto. - BD orientada a documentos - Escrita en C++ - Disponible en *nux (Linux, Solaris, etc), Windows y OS X - Muchos drivers (PHP, Java, Python, Ruby...)Saturday, June 16, 2012
  12. 12. Descripción - Documentos flexibles tipo JSON - Soporte completo de Indices - Queries complejos / Map Reduce - Framework de agregación (próximamente) - GridFS (almacena archivos nativamente) - Múltiples opciones de replicación - Sharding - Instalación sencilla con cero configuraciónSaturday, June 16, 2012
  13. 13. Orientada a Objetos ¿Vienes de SQL? Base de datos => Base de datos Tabla => Colección Fila => DocumentoSaturday, June 16, 2012
  14. 14. Documentos Tipo JSON { nombre: { primero: Juan, apellido: Perez }, titulo: Ingeniero, edad: 40 }Saturday, June 16, 2012
  15. 15. Sin Schema o Tablas Fijas { nombre: { primero: Juan, apellido: Perez }, titulo: Ingeniero, edad: 40, escuela: UJI }Saturday, June 16, 2012
  16. 16. Documentos Embebidos { "_id" : ObjectId("4ccba15ef597e9352e060000") "srcFilename" : "/etc/apache2/sites-enabled/example1.com", "vhostDirective" : { "directives" : [ { "name" : "CustomLog", "value" : "logs/example1.com-access_log combined" }, { "name" : "DocumentRoot", "value" : "/var/www/vhosts/example1.com/httpdocs" }, { "name" : "ServerName", "value" : "example1.com" } ] } }Saturday, June 16, 2012
  17. 17. Referencias Entre Documentos { "_id" : ObjectId("4cc4a5c3f597e9db6e010109"), "billingId" : NumberLong(650), "created" : ISODate("2010-10-24T21:31:47Z"), "servers" : [ { "$ref" : "server", "$id" : ObjectId("4cc4a5c4f597e9db6e050201") } ], "users" : [ { "$ref" : "user", "$id" : ObjectId("4cc4a5c4f597e9db6e980201") }, { "$ref" : "user", "$id" : ObjectId("4cc4a5c4f597e9db6e9c0201") } ] }Saturday, June 16, 2012
  18. 18. Indices db.personal.ensureIndex({nombre: 1}) db. personal.ensureIndex({nombre.primer: 1, nombre.apellido: 1}) db. personal.ensureIndex({edad: 0})Saturday, June 16, 2012
  19. 19. Indices db.personal.ensureIndex({nombre: 1}) db. personal.ensureIndex({nombre.primer: 1, nombre.apellido: 1}) db. personal.ensureIndex({edad: 0})Saturday, June 16, 2012
  20. 20. Indices db.personal.ensureIndex({nombre: 1}) db. personal.ensureIndex({nombre.primer: 1, nombre.apellido: 1}) db. personal.ensureIndex({edad: 0})Saturday, June 16, 2012
  21. 21. Consultas db. personal.find({nombre: Juan}) db. personal.find({tags: symfony}) db. personal.find({tags: {$in: [symfony, PHP]}}Saturday, June 16, 2012
  22. 22. Consultas db. personal.find({nombre: Juan}) db. personal.find({tags: symfony}) db. personal.find({tags: {$in: [symfony, PHP]}}Saturday, June 16, 2012
  23. 23. Consultas db. personal.find({nombre: Juan}) db. personal.find({tags: symfony}) db. personal.find({tags: {$in: [symfony, PHP]}}Saturday, June 16, 2012
  24. 24. GridFS - Archivos son divididos en “chunks” o partes y son guardados en múltiples documentos - API transparenteSaturday, June 16, 2012
  25. 25. Replicación Source: http://www.mongodb.org/display/DOCS/ReplicationSaturday, June 16, 2012
  26. 26. Shards Source: http://www.mongodb.org/display/DOCS/IntroductionSaturday, June 16, 2012
  27. 27. Simple instalación con cero configuración OS X wget http://fastdl.mongodb.org/osx/mongodb-osx-x86_64-2.0.4.tgz tar zxvf mongodb-osx-x86_64-2.0.4.tgz cd mongodb-osx-x86_64-2.0.4 ./mongodSaturday, June 16, 2012
  28. 28. Simple instalación con cero configuración CentOS Linux /etc/yum.repos.d/10gen.repo [10gen] name=10gen Repository baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64 gpgcheck=0 $ yum install -y mongo-stable-server $ service mongod startSaturday, June 16, 2012
  29. 29. Backups mongodump mongodump -u usuario -p pass mongorestore mongorestore -u usuario -p pass mongoexport mongoexport -u usuario -p pass mongoimport mongoimport -u usuario -p passSaturday, June 16, 2012
  30. 30. Monitoreo mongostatSaturday, June 16, 2012
  31. 31. Monitoreohttp://localhost:28017/Saturday, June 16, 2012
  32. 32. ¿Por qué MongoDB es bueno para el desarrollo rápido de aplicacones web?Saturday, June 16, 2012
  33. 33. Desarrollo Rápido de Aplicaciones Sin schema / orientada a documentos FLEXIBLE by exfordySaturday, June 16, 2012
  34. 34. Desarrollo Rápido de Aplicaciones Sin schema / orientada a documentos MIGRACIONES MAS FACILES by exfordySaturday, June 16, 2012
  35. 35. Desarrollo Rápido de Aplicaciones NO HAY JOINS!Saturday, June 16, 2012
  36. 36. Rendimiento VELOZ by xavi talledaSaturday, June 16, 2012
  37. 37. Rendimiento ESCALABILIDAD by Jimee, Jackie, Tom & AshaSaturday, June 16, 2012
  38. 38. Ojo al piojo! - No hay transacciones - No hay rollbacks - Valores inseguros por defecto - Locks en Map Reduce by Ernst VikneSaturday, June 16, 2012
  39. 39. Buenas aplicaciones - Sistema de manejo de contenidos (CMS) - Catálogos de productos - Análisis en tiempo real - Almacenamiento de logsSaturday, June 16, 2012
  40. 40. ySaturday, June 16, 2012
  41. 41. Driver de PECL Linux pecl install mongo echo “extension=mongo.so >> /path/php.ini” OS X http://php-osx.liip.ch/ Windows https://github.com/mongodb/mongo-php-driver/downloadsSaturday, June 16, 2012
  42. 42. Uso <?php // conectar $m = new Mongo(); // seleccionar una base de datos $db = $m->biblioteca; // seleccionar una coleccón $collection = $db->libros; // agregar un documento $obj = array( "titulo" => "RabbitMQ in Action", "autor" => "Alvaro Videla" ); $collection->insert($obj); // agregar otro documento con distintos datos $obj = array( "titulo" => "Desarrollo en Symfony", "pdf" => true ); $collection->insert($obj); // obtener todos los documentos en la colección $cursor = $collection->find(); // iterar los resultados foreach ($cursor as $obj) {     echo $obj["titulo"] . "n"; } ?>Saturday, June 16, 2012
  43. 43. Almacenamiento de Archivos <?php // guardar un archivo $id = $grid->storeFile("libro.pdf"); $libro = $grid->findOne(); // agregar un contador de descargas $libro->file[descargas] = 0; $grid->save($libro->file); // incrementar el contador $grid->update(array("_id" => $id), array($inc => array ("descargas" => 1))); ?>Saturday, June 16, 2012
  44. 44. Queries de SQL a Mongo http://php.net/manual/es/mongo.sqltomongo.phpSaturday, June 16, 2012
  45. 45. Interfaces de Administración - Genghis http://genghisapp.com/Saturday, June 16, 2012
  46. 46. Interfaces de Administración - RockMongo http://code.google.com/p/rock-php/wiki/rock_mongoSaturday, June 16, 2012
  47. 47. Interfaces de Administración - php-mongodb-admin https://github.com/jwage/php-mongodb-adminSaturday, June 16, 2012
  48. 48. Interfaces de Administración - mongohosting.com https://github.com/jwage/php-mongodb-adminSaturday, June 16, 2012
  49. 49. Librerias en PHP - Doctrine ODMSaturday, June 16, 2012
  50. 50. Librerias en PHP - Doctrine ODM - MandangoSaturday, June 16, 2012
  51. 51. Librerias en PHP - Doctrine ODM - Mandango - varias más...Saturday, June 16, 2012
  52. 52. Doctrine MongoDB ODM http://doctrine-project.org Doctrine MongoDB Object Document Mapper (ODM) está desarrollado para PHP 5.3.2+ y provee persistencia transparente de objetos PHP.Saturday, June 16, 2012
  53. 53. Doctrine MongoDB ODM Tipos de Mappings bin_data_custom float bin_data_func hash bin_data_md5 id bin_data int bin_data_uuid key boolean string date timestamp file incrementSaturday, June 16, 2012
  54. 54. Doctrine MongoDB ODM Tipos de Mappings bin_data_custom float bin_data_func hash bin_data_md5 id bin_data int bin_data_uuid key boolean string date timestamp file incrementSaturday, June 16, 2012
  55. 55. Doctrine MongoDB ODM Tipos de Mappings bin_data_custom float bin_data_func hash bin_data_md5 id bin_data int bin_data_uuid key boolean string date timestamp file incrementSaturday, June 16, 2012
  56. 56. Doctrine MongoDB ODM Tipos de Mappings bin_data_custom float bin_data_func hash bin_data_md5 id bin_data int bin_data_uuid key boolean string date timestamp file incrementSaturday, June 16, 2012
  57. 57. Doctrine MongoDB ODM Tipos de Mappings bin_data_custom float bin_data_func hash bin_data_md5 id bin_data int bin_data_uuid key boolean string date timestamp file incrementSaturday, June 16, 2012
  58. 58. Doctrine MongoDB ODM Tipos de Mappings bin_data_custom float bin_data_func hash bin_data_md5 id bin_data int bin_data_uuid key boolean string date timestamp file incrementSaturday, June 16, 2012
  59. 59. Doctrine MongoDB ODM Tipos de Mappings bin_data_custom float bin_data_func hash bin_data_md5 id bin_data int bin_data_uuid key boolean string date timestamp file incrementSaturday, June 16, 2012
  60. 60. Doctrine MongoDB ODM Tipos de Mappings bin_data_custom float bin_data_func hash bin_data_md5 id bin_data int bin_data_uuid key boolean string date timestamp file incrementSaturday, June 16, 2012
  61. 61. Doctrine MongoDB ODM Campos “AutoIncrement” <?php /** Document */ class MiClase { /** @Id(strategy="INCREMENT") */ private $id; public function getId() { return $this->id; } //... }Saturday, June 16, 2012
  62. 62. Doctrine MongoDB ODM Tipos propios <?php namespace MyProjectTypes; use DoctrineDBALTypesType; use DoctrineDBALPlatformsAbstractPlatform; /** * My custom datatype. */ class MyType extends Type { public function convertToPHPValue($value) { // This is executed when the value is read from the database. Make your conversions here. } public function convertToDatabaseValue($value) { // This is executed when the value is written to the database. Make your conversions here. } }Saturday, June 16, 2012
  63. 63. Doctrine MongoDB ODM Múltiples tipos en una misma colección /** * @Document(collection="documentos") * @DiscriminatorField(fieldName="type") * @DiscriminatorMap({"article"="Articulo", "album"="Album"}) */ class Articulo { // ... } /** * @Document(collection="documentos") * @DiscriminatorField(fieldName="type") * @DiscriminatorMap({"article"="Articulo", "album"="Album"}) */ class Album { // ... }Saturday, June 16, 2012
  64. 64. Doctrine MongoDB ODM /** @Document */ class Usuario { /** @Id */ private $id; /** @String */ private $nombre; /** @String */ private $email; /** @ReferenceMany(targetDocument="Articulo", cascade="all") */ private $articulos = array(); // ... }Saturday, June 16, 2012
  65. 65. Doctrine MongoDB ODM /** @Document */ class Articulo { /** @Id */ private $id; /** @String */ private $titulo; /** @String */ private $contenido; /** @Date */ private $createdAt; // ... }Saturday, June 16, 2012
  66. 66. Doctrine MongoDB ODM <?php // crear un usuario $user = new Usuario(); $user->setNombre(Juan P.); $user->setEmail(email@example.com); // avisale a Doctrine2 que guarde $usuario en el próximo flush() $dm->persist($usuario); // crear un articulo $articulo = new Articulo(); $articulo->setTitulo(Mi primer articulo); $articulo->setContenido(MongoDB + Doctrine 2 ODM = espectacular!); $articulo->setCreatedAt(new DateTime()); $user->agregarArticulo($articulo); // guarda todo en MongoDB $dm->flush();Saturday, June 16, 2012
  67. 67. Doctrine MongoDB ODM <?php // crear un usuario $usuario = new Usuario(); $usuario->setNombre(Juan P.); $usuario->setEmail(email@example.com); // avisale a Doctrine2 que guarde $usuario en el próximo flush() $dm->persist($usuario); // crear un articulo $articulo = new Articulo(); $articulo->setTitulo(Mi primer articulo); $articulo->setContenido(MongoDB + Doctrine 2 ODM = espectacular!); $articulo->setCreatedAt(new DateTime()); $user->addArticulo($articulo); // guarda todo en MongoDB $dm->flush($usuario);Saturday, June 16, 2012
  68. 68. Doctrine MongoDB ODM <?php // crear un usuario $user = new Usuario(); $user->setNombre(Juan P.); $user->setEmail(email@example.com); // avisale a Doctrine2 que guarde $usuario en el próximo flush() $dm->persist($usuario); // crear un articulo $articulo = new Articulo(); $articulo->setTitulo(Mi primer articulo); $articulo->setContenido(MongoDB + Doctrine 2 ODM = espectacular!); $articulo->setCreatedAt(new DateTime()); $user->agregarArticulo($articulo); // guarda todo en MongoDB $dm->flush($usuario, false);Saturday, June 16, 2012
  69. 69. Doctrine MongoDB ODM Array ( [_id] => 4bec5869fdc212081d000000 [titulo] => My First Blog Post [contenido] => MongoDB + Doctrine 2 ODM = awesomeness! [createdAt] => MongoDate Object ( [sec] => 1273723200 [usec] => 0 ) )Saturday, June 16, 2012
  70. 70. Doctrine MongoDB ODM Array ( [_id] => 4bec5869fdc212081d010000 [nombre] => Bulat S. [email] => email@example.com [articulos] => Array ( [0] => Array ( [$ref] => Articulo [$id] => 4bec5869fdc212081d000000 [$db] => test_database ) ) )Saturday, June 16, 2012
  71. 71. Doctrine MongoDB ODM $usuario = $dm->find(Usuario, $idDelUsuario); $usuario = $dm->getRepository(Usuario)->findOneByNombre(Juan); $articulos = $usuario->getArticulos(); foreach ($articulos as $articulo) { echo $articulo; }Saturday, June 16, 2012
  72. 72. Doctrine MongoDB ODM Repositorios de documents // src/TuNamespace/TuBundle/ServerRepository.php namespace TuNamespaceTuBundle; use DoctrineODMMongoDBDocumentRepository; class ServerRepository extends DocumentRepository { public function getActiveServers() { return $this->createQueryBuilder() ->field(isActive)->equals(true) ->sort(name, asc)->getQuery()->execute(); } Usage $rep = $dm->getRepository(‘@TuBundle/Server’); $servers = $rep->getActiveServers();Saturday, June 16, 2012
  73. 73. Doctrine MongoDB ODM /** @Document */ class Imagen { /** @Id */ private $id; /** @Field */ private $nombre; /** @File */ private $file;Saturday, June 16, 2012
  74. 74. Doctrine MongoDB ODM // guardar archivo $imagen = new Imagen(); $imagen->setNombre(Imagen de prueba); $imagen->setFile(/path/to/imagen.png); $dm->persist($imagen); $dm->flush(); // obtener documento y enviar archivo al cliente HTTP $imagen = $dm->createQueryBuilder(DocumentsImagen) ->field(nombre)->equals(Imagen de prueba) ->getQuery() ->getSingleResult(); header(Content-type: image/png;); echo $imagen->getFile()->getBytes();Saturday, June 16, 2012
  75. 75. Saturday, June 16, 2012
  76. 76. ¡No necesita introducción!Saturday, June 16, 2012
  77. 77. Bundles de Symfony2 - DoctrineMongoDBBundleSaturday, June 16, 2012
  78. 78. Bundles de Symfony2 - DoctrineMongoDBBundle - MandangoBundleSaturday, June 16, 2012
  79. 79. DoctrineMongoDBBundle Instalación en Symfony 2.0 deps [doctrine-mongodb] git=http://github.com/doctrine/mongodb.git [doctrine-mongodb-odm] git=http://github.com/doctrine/mongodb-odm.git [DoctrineMongoDBBundle] git=http://github.com/doctrine/DoctrineMongoDBBundle.git target=/bundles/Symfony/Bundle/DoctrineMongoDBBundle version=v2.0.0 $ ./bin/vendors installSaturday, June 16, 2012
  80. 80. DoctrineMongoDBBundle Instalación en Symfony 2.1 con Composer composer.json { require: { "doctrine/mongodb-odm-bundle": "dev-master" } } $ php composer.phar updateSaturday, June 16, 2012
  81. 81. DoctrineMongoDBBundle Configurando Symfony2.1 app/autoload.php use DoctrineCommonAnnotationsAnnotationRegistry; AnnotationRegistry::registerFile(__DIR__./../vendor/doctrine/ mongodb-odm/lib/Doctrine/ODM/MongoDB/Mapping/Annotations/ DoctrineAnnotations.php);Saturday, June 16, 2012
  82. 82. DoctrineMongoDBBundle Configurando Symfony2.1 app/config/config.yml doctrine_mongodb: connections: default: server: mongodb://localhost:27017 options: connect: true default_database: test_database document_managers: default: auto_mapping: trueSaturday, June 16, 2012
  83. 83. DoctrineMongoDBBundle app/config/config.yml doctrine_mongodb: connections: default: server: mongodb://localhost:27017 options: connect: true usage: server: mongodb://user:pass@db1.mongohosting.com:27017 options: replicaSet: true connect: true default_database: test_database document_managers: default: mappings: SGCBundle: ~ SGCRepositoryAppBundle: yml MiBundle: { type: xml, dir: Resources/config/doctrine/ mapping }Saturday, June 16, 2012
  84. 84. DoctrineMongoDBBundle Definiendo DocumentosSaturday, June 16, 2012
  85. 85. DoctrineMongoDBBundle Definiendo Documentos // src/Acme/StoreBundle/Document/Product.php namespace AcmeStoreBundleDocument; use DoctrineODMMongoDBMappingAnnotations as MongoDB; /** * @MongoDBDocument(collection="product") */ class Product { /** * @MongoDBId */ protected $id; /** * @MongoDBString @MongoDBIndex(unique=true, order="asc") */ protected $name;Saturday, June 16, 2012
  86. 86. DoctrineMongoDBBundle Usando Documentos // src/Acme/StoreBundle/Controller/DefaultController.php use AcmeStoreBundleDocumentProduct; use SymfonyComponentHttpFoundationResponse; // ... public function createAction() { $product = new Product(); $product->setName(A Foo Bar); $product->setPrice(19.99); $dm = $this->get(doctrine.odm.mongodb.document_manager); $dm->persist($product); $dm->flush(); return new Response(Created product id .$product->getId()); }Saturday, June 16, 2012
  87. 87. DoctrineMongoDBBundle Consumiendo Mongo directamente // src/Acme/StoreBundle/Controller/DefaultController.php use SymfonyComponentHttpFoundationResponse; // ... public function createAction() { $dm = $this->get(doctrine.odm.mongodb.document_manager); $mongo = $dm->getConnection()->getMongo()); $resultado = $mongo->miBD->miColleccion->find(); ...Saturday, June 16, 2012
  88. 88. Formularios Debido a que los documentos son objetos simples de PHP, integrar los formularios es extremadamente sencillo.public function createAction(){ $dm = $this->get(doctrine.odm.mongodb.default_document_manager); $form = $this->createForm(new RegistrationType(), new Registration()); $form->bindRequest($this->getRequest()); if ($form->isValid()) { $registration = $form->getData(); $dm->persist($registration->getUser()); $dm->flush(); return $this->redirect(...); } http://symfony.com/doc/master/bundles/DoctrineMongoDBBundle/form.htmlSaturday, June 16, 2012
  89. 89. Comandos Comandos de Symfony2 doctrine doctrine:mongodb:cache:clear-metadata Clear all metadata cache for a document manager. doctrine:mongodb:fixtures:load Load data fixtures to your database. doctrine:mongodb:generate:documents Generate document classes and method stubs from your mapping information. doctrine:mongodb:generate:hydrators Generates hydrator classes for document classes. doctrine:mongodb:generate:proxies Generates proxy classes for document classes. doctrine:mongodb:generate:repositories Generate repository classes from your mapping information. doctrine:mongodb:mapping:info Show basic information about all mapped documents. doctrine:mongodb:query Query mongodb and inspect the outputted results from your document classes. doctrine:mongodb:schema:create Allows you to create databases, collections and indexes for your documents doctrine:mongodb:schema:drop Allows you to drop databases, collections and indexes for your documentsSaturday, June 16, 2012
  90. 90. Bundles que usan MongoDB - SonataDoctrineMongoDBAdminBundle - IsmaAmbrosiGeneratorBundle - EbutikMongoSessionBundle - TranslationEditorBundle - ServerGroveLiveChatSaturday, June 16, 2012
  91. 91. ¿Preguntas?Saturday, June 16, 2012
  92. 92. ¡Muchas Gracias! Transparencias: http://slideshare.net/pgodel Twitter: @pgodelSaturday, June 16, 2012

×