SlideShare a Scribd company logo
1 of 116
Download to read offline
Pablo Godel @pgodel - MidwestPHP 2013
             March 2nd 2013 - St. Paul, MN
                  https://joind.in/8211




Sunday, March 3, 13
Who Am I?

    ⁃ Born in Argentina, living in the US since 1999
    ⁃ PHP & Symfony developer
    ⁃ Founder of the original PHP mailing list in spanish
    ⁃ Master of the parrilla




Sunday, March 3, 13
Sunday, March 3, 13
Sunday, March 3, 13
ServerGrove!

      ⁃ Founded ServerGrove Networks in 2005

      ⁃ Provider of web hosting specialized in PHP,
        Symfony, ZendFramework, and others

      ⁃ Mongohosting.com!

      ⁃ Servers in Miami, FL and Dublin, Ireland




Sunday, March 3, 13
Community is our teacher

            ⁃ Very active open source supporter through code
              contributions and usergroups/conference sponsoring




Sunday, March 3, 13
Agenda


                      - Introduction to MongoDB
                      - PHP and MongoDB
                      - PHP Libraries
                      - Introduction to Symfony2
                      - Symfony2 and MongoDB




Sunday, March 3, 13
What is MongoDB?




                       Who is 10Gen?




Sunday, March 3, 13
Mongo
                      Mongo as in "humongous". Used to describe
                      something extremely large or important.




Sunday, March 3, 13
MongoDB is a scalable, high-performance,
            open source NoSQL database.

    - Document Oriented DB
    - Written in C++
    - Available for *nux (Linux, Solaris, etc),
       Windows and OS X
    - Lots of Drivers (PHP, Java, Python, Ruby...)




Sunday, March 3, 13
Features

         - Flexible JSON-style documents
         - Full Indexing
         - Complex Queries / Map Reduce
         - Aggregation Framework
         - GridFS (store files natively)
         - Multiple Replication Options
         - Sharding
         - Simple Installation / Zero Config




Sunday, March 3, 13
Document Oriented


 Coming from SQL?




                            Database => Database
                            Table => Collection
                            Row => Document




Sunday, March 3, 13
JSON-style documents
    {
         name: {
                   first: 'John',
                   last: 'Doe'
                  },
         title: 'Engineer',
         age: 40
  }




Sunday, March 3, 13
No Schema or fixed tables

     {
         name: {
                   first: 'Foo',
                   last: 'Bar'
                  },
         title: 'Student',
         school: 'Harvard'
  }




Sunday, March 3, 13
Embedded documents
   {
    "_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"
                       }
                     ]
           }
   }




Sunday, March 3, 13
Document Referencing
    {
    "_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")
       }
    ]
    }



Sunday, March 3, 13
Full Indexing



                 db.coll.ensureIndex({name.last: 1})

                 db.coll.ensureIndex({name.first: 1, name.last: 1})

                 db.coll.ensureIndex({age: 0})




Sunday, March 3, 13
Querying



                      db.coll.find({name: 'John'})

                      db.coll.find({keywords: 'storage'})

                      db.coll.find({keywords: {$in: ['storage', 'DBMS']}}




Sunday, March 3, 13
GridFS




                      - Files are divided in chunks
                        and stored over multiple documents

                      - Transparent API
        $grid->storeFile("/path/to/somefile.txt", 
                 array("metadata" => array("date" => new MongoDate())));




Sunday, March 3, 13
Replication




                      Source: http://www.mongodb.org/display/DOCS/Replication

Sunday, March 3, 13
Shards




                      Source: http://www.mongodb.org/display/DOCS/Introduction

Sunday, March 3, 13
Simple Installation/Zero Config



                                 OS X


        wget http://fastdl.mongodb.org/osx/mongodb-osx-x86_64-2.2.3.tgz

        tar zxvf mongodb-osx-x86_64-2.2.3.tgz

        cd mongodb-osx-x86_64-2.2.3

        ./mongod




Sunday, March 3, 13
Simple Installation/Zero Config


                                   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-10gen-server
  $ service mongod start




Sunday, March 3, 13
Why is MongoDB good
                      for Rapid Development
                      of Web Apps?




Sunday, March 3, 13
Rapid Development
                      Schema-less / Document Oriented



                                                  FLEXIBILITY




     by exfordy




Sunday, March 3, 13
Rapid Development
                      Schema-less / Document Oriented



                                                   EASIER
                                                 MIGRATIONS




     by exfordy




Sunday, March 3, 13
Rapid Development


                                          NO JOINS!




Sunday, March 3, 13
Performance


                                      SPEED




      by xavi talleda




Sunday, March 3, 13
Performance


                                                  SCALABILITY




     by Jimee, Jackie, Tom & Asha




Sunday, March 3, 13
A Word of Caution


                                     No Transactions
                                      No Rollbacks
                                     Unsafe defaults
                                    Map Reduce locks




     by Ernst Vikne




Sunday, March 3, 13
Great Use Cases

            - Content Management
            - Product Catalogs
            - Realtime Analytics
            - Logs Storage

Sunday, March 3, 13
and




Sunday, March 3, 13
PECL driver

 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/downloads



Sunday, March 3, 13
Attention


                            Mongo 1.2.x
                      $m = new Mongo();

                       Mongo 1.3.x
$m = new MongoClient();




Sunday, March 3, 13
Usage
 <?php
 // connect
 $m = new MongoClient();
 // select a database
 $db = $m->comedy;
 // select a collection (analogous to a relational database's table)
 $collection = $db->cartoons;
 // add a record
 $obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watte
 rson" );
 $collection->insert($obj);
 // add another record, with a different "shape"
 $obj = array( "title" => "XKCD", "online" => true );
 $collection->insert($obj);
 // find everything in the collection
 $cursor = $collection->find();
 // iterate through the results
 foreach ($cursor as $obj) {
     echo $obj["title"] . "n";
 }
 ?>


Sunday, March 3, 13
Storing Files
          <?php

          // save a file
          $id = $grid->storeFile("game.tgz");
          $game = $grid->findOne();

          // add a downloads counter
          $game->file['downloads'] = 0;
          $grid->save($game->file);

          // increment the counter
          $grid-
          >update(array("_id" => $id), array('$inc' => array("downloads
          " => 1)));

          ?>




Sunday, March 3, 13
SQL to Mongo Queries
                      SQL to Mongo Mapping Chart
                      This is a PHP-specific version of the » SQL to Mongo mapping chart in the main docs.



                                                                   SQL Statement
                                                          Mongo Query Language Statement
                      CREATE TABLE USERS (a Number, b Number)
                      Implicit or use MongoDB::createCollection().
                      INSERT INTO USERS VALUES(1,1)
                      $db->users->insert(array("a" => 1, "b" => 1));
                      SELECT a,b FROM users
                      $db->users->find(array(), array("a" => 1, "b" => 1));
                      SELECT * FROM users WHERE age=33
                      $db->users->find(array("age" => 33));
                      SELECT a,b FROM users WHERE age=33
                      $db->users->find(array("age" => 33), array("a" => 1, "b" => 1));
                      SELECT a,b FROM users WHERE age=33 ORDER BY name
                      $db->users->find(array("age" => 33), array("a" => 1, "b" => 1))->sort(array("name" => 1));
                      SELECT * FROM users WHERE age>33
                      $db->users->find(array("age" => array('$gt' => 33)));
                      SELECT * FROM users WHERE age<33
                      $db->users->find(array("age" => array('$lt' => 33)));
                      SELECT * FROM users WHERE name LIKE "%Joe%"
                      $db->users->find(array("name" => new MongoRegex("/Joe/")));
                      SELECT * FROM users WHERE name LIKE "Joe%"
                      $db->users->find(array("name" => new MongoRegex("/^Joe/")));
                      SELECT * FROM users WHERE age>33 AND age<=40
                      $db->users->find(array("age" => array('$gt' => 33, '$lte' => 40)));
                      SELECT * FROM users ORDER BY name DESC



                               http://php.net/manual/en/
                                 mongo.sqltomongo.php
Sunday, March 3, 13
Admin Interfaces


          - Genghis
            http://genghisapp.com/

          - RockMongo
            http://code.google.com/p/rock-php/wiki/rock_mongo

          - php-mongodb-admin
            https://github.com/jwage/php-mongodb-admin




Sunday, March 3, 13
PHP Libraries


                      - Doctrine ODM
                       Doctrine MongoDB Object Document Mapper is built for PHP
                       5.3.2+ and provides transparent persistence for PHP objects.




                      - Mandango
                       Mandango is a simple, poweful and ultrafast Object Document
                       Mapper (ODM) for PHP and MongoDB.




                      - many more...



Sunday, March 3, 13
Doctrine MongoDB ODM



                      http://doctrine-project.org

    Doctrine MongoDB Object Document Mapper is
     built for PHP 5.3.2+ and provides transparent
               persistence for PHP objects.



Sunday, March 3, 13
Doctrine MongoDB ODM
  /** @Document */
  class User
  {
      /** @Id */
      private $id;

            /** @String */
            private $name;

            /** @String */
            private $email;

            /** @ReferenceMany(targetDocument="BlogPost", cascade="all") */
            private $posts;

            // ...
  }




Sunday, March 3, 13
Doctrine MongoDB ODM
  /** @Document */
  class BlogPost
  {
      /** @Id */
      private $id;

            /** @String */
            private $title;

            /** @String */
            private $body;

            /** @Date */
            private $createdAt;

            // ...
  }




Sunday, March 3, 13
Doctrine MongoDB ODM
  <?php

  // create user
  $user = new User();
  $user->setName('Bulat S.');
  $user->setEmail('email@example.com');

  // tell Doctrine 2 to save $user on the next flush()
  $dm->persist($user);

  // create blog post
  $post = new BlogPost();
  $post->setTitle('My First Blog Post');
  $post->setBody('MongoDB + Doctrine 2 ODM = awesomeness!');
  $post->setCreatedAt(new DateTime());

  $user->addPost($post);

  // store everything to MongoDB
  $dm->flush();




Sunday, March 3, 13
Doctrine MongoDB ODM

    Array
    (
        [_id] => 4bec5869fdc212081d000000
        [title] => My First Blog Post
        [body] => MongoDB + Doctrine 2 ODM = awesomeness!
        [createdAt] => MongoDate Object
            (
                [sec] => 1273723200
                [usec] => 0
            )
    )




Sunday, March 3, 13
Doctrine MongoDB ODM
  Array
  (
      [_id] => 4bec5869fdc212081d010000
      [name] => Bulat S.
      [email] => email@example.com
      [posts] => Array
          (
              [0] => Array
                  (
                       [$ref] => blog_posts
                       [$id] => 4bec5869fdc212081d000000
                       [$db] => test_database
                  )
          )
  )




Sunday, March 3, 13
Doctrine MongoDB ODM
  Retrieving Persisted Objects
  $user = $dm->find('User', $userId);

  $user = $dm->getRepository('User')->findOneByName('Bulat S.');

  $posts = $user->getPosts();
  foreach ($posts as $post) {
     echo $post;
  }




Sunday, March 3, 13
Doctrine MongoDB ODM
  Document Repositories
  // src/YourNamespace/YourBundle/ServerRepository.php
  namespace YourNamespaceYourBundle;

  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(‘@YourBundle/Server’);
  $servers = $rep->getActiveServers();


Sunday, March 3, 13
Doctrine MongoDB ODM
  /** @Document */
  class Image
  {
      /** @Id */
      private $id;

            /** @Field */
            private $name;

            /** @File */
            private $file;




Sunday, March 3, 13
Doctrine MongoDB ODM
  // store file
  $image = new Image();
  $image->setName('Test image');
  $image->setFile('/path/to/image.png');

  $dm->persist($image);
  $dm->flush();


  // retrieve and return file to client
  $image = $dm->createQueryBuilder('DocumentsImage')
      ->field('name')->equals('Test image')
      ->getQuery()
      ->getSingleResult();

  header('Content-type: image/png;');
  echo $image->getFile()->getBytes();




Sunday, March 3, 13
Tips: Doctrine MongoDB ODM


              // Eager ID creation

              public function __construct()
              {
                  $this->id = (string) new MongoId();
              }




Sunday, March 3, 13
Tips: Doctrine MongoDB ODM


              // Creation date

              public function __construct()
              {
                  $this->id = (string) new MongoId();
                  $this->createdDt = new DateTime();
              }




Sunday, March 3, 13
Tips: Doctrine MongoDB ODM


              // ArrayCollections

              public function __construct()
              {
                  $this->id = (string) new MongoId();
                  $this->createdDt = new DateTime();
                  $this->entries = new ArrayCollection();
              }




Sunday, March 3, 13
Tips: Doctrine MongoDB ODM


              // Space Saving

                      /** @String(name=”n”) */
                      private $name;

                      /** @String(name=”e”) */
                      private $email;




Sunday, March 3, 13
Symfony is a PHP Web Development Framework.



Sunday, March 3, 13
“First, Symfony2 is a reusable set of standalone, decoupled,
    and cohesive PHP components that solve common web
                     development problems.
         Then, based on these components, Symfony2 is also a
                      full-stack web framework.”




                      http://fabien.potencier.org/article/49/what-is-symfony2
Sunday, March 3, 13
25 High Quality
                       Components




Sunday, March 3, 13
Symfony 2 Components

                      •   DependencyInjection                    •   Serializer
                      •   EventDispatcher                        •   Validator
                      •   HttpFoundation                         •   Security
                      •   DomCrawler                             •   Routing
                      •   ClassLoader                            •   Console
                      •   CssSelector                            •   Process
                      •   HttpKernel                             •   Config
                      •   BrowserKit                             •   Finder
                      •   Templating                             •   Locale
                      •   Translation                            •   Yaml
                      •   Serializer                             •   Form
                                                                 •   More...


                             All of them at GitHub: http://github.com/symfony

Sunday, March 3, 13
Symfony 2 Components


   Components Documentation
   http://symfony.com/doc/current/components/index.html



    Blog post series about creating a framework based on
    the Symfony2 Components
     http://fabien.potencier.org/




Sunday, March 3, 13
Symfony 2 Highlights

  •   Rewritten from scratch for PHP 5.3
  •   Based on the HTTP specification
  •   Very stable and solid API
  •   Extensible through the creation of Bundles (replacement for
      sf1 plugins)
  •   Flexible configuration using YAML, XML, annotations or
      PHP
  •   All configuration is compiled to PHP code and cached
  •   Lots of unit tests
  •   Source code audited by independent security firm thanks to
      donations of the Symfony Community




Sunday, March 3, 13
Symfony 2 Highlights

  • Extensible Configuration with Service Container/
    Dependency Injection
  • Complete redesign of Forms support
  • Validations
  • Extensible Security with Authentication/Authorization
  • Advanced and powerful templating through Twig
  • Routes configured with YAML, XML or Annotations
  • ESI Caching support out of the box
  • Assets management with Assetic
  • Translations
  • Environments




Sunday, March 3, 13
Symfony 2 Highlights: Community


    • 698 developers contributed to Symfony2
    • 7000+ pull requests
    • 969 1901 bundles at knpbundles.com
    • Very active IRC and mailing lists support
      channels
    • Community Gamification through
      SensioLabs Connect
    • Symfony2 Ecosystem


Sunday, March 3, 13
Symfony 2 Highlights: Bundles




Sunday, March 3, 13
Symfony 2 Getting Started




http://symfony.com/download




Sunday, March 3, 13
Symfony 2 Getting Started



                      tar zxf Symfony_Standard_Vendors_2.2.0.tgz


                                          or



                       unzip Symfony_Standard_Vendors_2.2.0.zip


Sunday, March 3, 13
Symfony 2 Getting Started with Composer



              $ curl -s https://getcomposer.org/installer | php


              $ php composer.phar create-project 
              symfony/framework-standard-edition path/ 2.2.0




                           http://getcomposer.org/
Sunday, March 3, 13
Symfony 2 Getting Started




            Distributions

                      A Symfony distribution is made up of Symfony2
                           components, a selection of bundles,
                       a directory structure, a default configuration.




                                    http://symfony.com/distributions
Sunday, March 3, 13
Symfony 2 Getting Started

    Symfony Standard Distribution
      • Directory structure
      • Default configuration
      • Bundles
         ⁃ DoctrineBundle
         ⁃ JMSSecurityExtraBundle
         ⁃ SensioDistributionBundle
         ⁃ SensioFrameworkExtraBundle
         ⁃ SensioGeneratorBundle
         ⁃ AsseticBundle



                         http://symfony.com/distributions
Sunday, March 3, 13
Symfony 2 Getting Started




Sunday, March 3, 13
Symfony 2 Getting Started




Sunday, March 3, 13
Symfony 2 Directory Structure




Sunday, March 3, 13
Symfony 2 Directory Structure




Sunday, March 3, 13
Symfony 2 Directory Structure




Sunday, March 3, 13
Symfony 2 Directory Structure




Sunday, March 3, 13
Symfony 2 Configuration: app/config.yml




Sunday, March 3, 13
Symfony 2
     Configuration: app/parameters.ini




Sunday, March 3, 13
Symfony 2
     Configuration: app/config_dev.yml




Sunday, March 3, 13
Browser

                        Request


       Bootstrap (app.php)

                      Controller

                       Template             Response
                      Want to know more? Go to Raul Fraile’s
                            Symfony2 Internals Talk
Sunday, March 3, 13
Bootstrap (app.php)




Sunday, March 3, 13
Symfony 2 Bootstrap File - web/app.php




Sunday, March 3, 13
Controllers




Sunday, March 3, 13
Symfony 2 Controllers




Sunday, March 3, 13
Controllers




Sunday, March 3, 13
Sunday, March 3, 13
Templates




Sunday, March 3, 13
Symfony 2 Templating / Twig
                      Comments: {# comments are not rendered #}

                                 {# multi-line comments!
                                    {{ var }}
                                 #}

     Output variables: {{ var }}
                       {{ var | upper }}
                       {{ var | raw }}
                       {{ object.property }}
                       {{ true ? ‘yes’ : ‘no’ }}
                            http://twig.sensiolabs.org/
Sunday, March 3, 13
Symfony 2 Templating / Twig

  Blocks: {% set var = ‘hello’ %}
          {% set foo = var ~ ’ and goodbye’ %}

                      {% if foo is ‘bar’ %}
                         ...
                      {% else %}
                         ...
                      {% endif %}



                           http://twig.sensiolabs.org/
Sunday, March 3, 13
Symfony 2 Templating / Twig

  Blocks: {% for key, val in list %}

                         {{ loop.index }}. {{ val }}

                      {% else %}

                         No keys.

                      {% endfor %}


                            http://twig.sensiolabs.org/
Sunday, March 3, 13
Symfony 2 Templating / Twig
Extends:
                      {% extends "Bundle::layout.html.twig" %}


 Include:
                      {% include “Bundle:Demo:template.html.twig” %}


  Render:
                      {% render “Bundle:Demo:action” %}


                          http://twig.sensiolabs.org/
Sunday, March 3, 13
Awesome Twig Presentations

  Twig, The Flexible, Fast and Secure Template Language
  for PHP - Fabien Potencier
  http://www.slideshare.net/fabpot/twig-the-flexible-fast-and-securetemplate-
  language-for-php



  Being Dangerous with Twig - Ryan Weaver
  http://slideshare.net/weaverryan/being-dangerous-with-twig-symfony-
  live-paris



  Twig avanzado - Javier Eguiluz
   http://www.slideshare.net/javier.eguiluz/twig-avanzado-sf2vigo (Spanish)




Sunday, March 3, 13
Symfony 2 layout.html.twig




Sunday, March 3, 13
Symfony 2 index.html.twig




Sunday, March 3, 13
Symfony 2 index.html.twig




Sunday, March 3, 13
Bundles




Sunday, March 3, 13
Symfony 2 Bundles




                      Everything in Symfony2 is
                        contained in Bundles




Sunday, March 3, 13
Symfony 2 Bundles




                         Even Symfony2 is
                      a collection of Bundles




Sunday, March 3, 13
Symfony 2 Directory Structure




Sunday, March 3, 13
Symfony 2 Bundles Registration
            app/AppKernel.php




Sunday, March 3, 13
Symfony 2 Bundles for MongoDB



                      - DoctrineMongoDBBundle

                      - MandangoBundle




Sunday, March 3, 13
Symfony 2
     Installing DoctrineMongoDBBundle

               Installation with Composer
               composer.json
                {
                      require": {
                          "doctrine/mongodb-odm-bundle": "3.0.*"
                      },
                      "minimum-stability": "dev"
                }



                $ php composer.phar update



                $ php composer.phar install doctrine/mongodb-odm-bundle




Sunday, March 3, 13
Symfony 2
     Installing DoctrineMongoDBBundle

               Installation with Composer



                  $ php composer.phar require 
                   doctrine/mongodb-odm-bundle:3.0.*




Sunday, March 3, 13
Symfony 2
   Configuring DoctrineMongoDBBundle


  app/autoload.php

 // app/autoload.php
 use DoctrineODMMongoDBMappingDriverAnnotationDriver;
 AnnotationDriver::registerAnnotationClasses();




Sunday, March 3, 13
Symfony 2
   Configuring DoctrineMongoDBBundle

 app/config/config.yml
 doctrine_mongodb:
     connections:
         default:
             server: mongodb://localhost:27017
             options:
                  connect: true
     default_database: test_database
     document_managers:
         default:
             auto_mapping: true




Sunday, March 3, 13
Symfony 2
   Multiple Connections & Bundle Mappings
 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
                MyBundle: { type: xml, dir: Resources/config/doctrine/
 mapping }


Sunday, March 3, 13
Symfony 2 Defining Documents




Sunday, March 3, 13
Symfony 2 Defining Documents

 // 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;



Sunday, March 3, 13
Symfony 2 Using Documents

 // 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_mongodb')->getManager();
           $dm->persist($product);
           $dm->flush();

           return new Response('Created product id '.$product->getId());
 }




Sunday, March 3, 13
Symfony 2 Forms
        Since Documents are Plain PHP Objects integrating it with Symfony Forms is straightforward.

   public function createAction()
   {
       $dm = $this->get('doctrine_mongodb')->getManager();

       $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.html




Sunday, March 3, 13
Symfony 2 ODM Commands

 Symfony2 Commands
 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 documents




Sunday, March 3, 13
TIP: Storing Symfony Sessions in MongoDB

  app/config/config.yml




Sunday, March 3, 13
TIP: Mixing Doctrine ODM & ORM



                         Order             Product
                      Entity (ORM)     Document (ODM)



           http://docs.doctrine-project.org/projects/doctrine-
          mongodb-odm/en/latest/cookbook/blending-orm-and-
                          mongodb-odm.html



Sunday, March 3, 13
TIP: Persisting objects with ODM or ORM
 <?php

 namespace DoctrineBlog;

 /** @Entity(repositoryClass="DoctrineBlogORMBlogPostRepository")
 */
 class BlogPost
 {
     /** @Id @Column(type="integer") */
     private $id;

           /** @Column(type="string") */
           private $title;

           /** @Column(type="text") */
           private $body;

           // ...
 }




Sunday, March 3, 13
TIP: Persisting objects with ODM or ORM
 <?php

 namespace Documents;

 /** @Document(repositoryClass="DoctrineBlogODMMongoDB
 BlogPostRepository") */
 class BlogPost
 {
     /** @Id */
     private $id;

           /** @Field(type="string") */
           private $title;

           /** @Field(type="string") */
           private $body;

           // ...
 }




Sunday, March 3, 13
Symfony 2 Bundles using MongoDB



               - SonataDoctrineMongoDBAdminBundle
               - IsmaAmbrosiGeneratorBundle
               - TranslationEditorBundle
               - ServerGroveLiveChat




Sunday, March 3, 13
Additional Resources



       - http://php.net/mongo
       - http://docs.mongodb.org/manual/
       - http://symfony.com/doc/current/index.html
       - http://www.doctrine-project.org/docs/mongodb-odm




Sunday, March 3, 13
Questions?




Sunday, March 3, 13
Thank you!




                 Rate Me Please! https://joind.in/8211
                      Slides: http://slideshare.net/pgodel
                               Twitter: @pgodel
                       E-mail: pablo@servergrove.com
Sunday, March 3, 13

More Related Content

Viewers also liked

Symfony2 and MongoDB
Symfony2 and MongoDBSymfony2 and MongoDB
Symfony2 and MongoDBPablo Godel
 
Getting started with MongoDB and PHP
Getting started with MongoDB and PHPGetting started with MongoDB and PHP
Getting started with MongoDB and PHPgates10gen
 
MongoDB and the MEAN Stack
MongoDB and the MEAN StackMongoDB and the MEAN Stack
MongoDB and the MEAN StackMongoDB
 
Back 2 School Night 2011
Back 2 School Night 2011Back 2 School Night 2011
Back 2 School Night 2011jmori1
 
iPad Apps for Attorneys
iPad Apps for AttorneysiPad Apps for Attorneys
iPad Apps for Attorneysfront9tech
 
Механизмы адаптации организма к гипоксии
Механизмы адаптации организма к гипоксииМеханизмы адаптации организма к гипоксии
Механизмы адаптации организма к гипоксииcrasgmu
 
KGI Knauf insulation plafonds (1)
KGI Knauf insulation plafonds (1)KGI Knauf insulation plafonds (1)
KGI Knauf insulation plafonds (1)Quietroom Label
 
الفيروسات
الفيروساتالفيروسات
الفيروساتlmooo
 
dealomio - or why simple products rule (mobile monday Berlin)
dealomio - or why simple products rule (mobile monday Berlin)dealomio - or why simple products rule (mobile monday Berlin)
dealomio - or why simple products rule (mobile monday Berlin)dealomio
 
Основы электрофизиологии
Основы электрофизиологииОсновы электрофизиологии
Основы электрофизиологииcrasgmu
 
PS - sejarah public speaking
PS - sejarah public speakingPS - sejarah public speaking
PS - sejarah public speakingZainal Muttaqin
 
Investment Support Network
Investment Support NetworkInvestment Support Network
Investment Support Networkisn_dubai
 
Globalisation 100119101548-phpapp01
Globalisation 100119101548-phpapp01Globalisation 100119101548-phpapp01
Globalisation 100119101548-phpapp01Mehak Sukhramani
 
Classification of Matter Overview
Classification of Matter OverviewClassification of Matter Overview
Classification of Matter Overviewjmori1
 

Viewers also liked (20)

Symfony2 and MongoDB
Symfony2 and MongoDBSymfony2 and MongoDB
Symfony2 and MongoDB
 
Getting started with MongoDB and PHP
Getting started with MongoDB and PHPGetting started with MongoDB and PHP
Getting started with MongoDB and PHP
 
MongoDB and the MEAN Stack
MongoDB and the MEAN StackMongoDB and the MEAN Stack
MongoDB and the MEAN Stack
 
Back 2 School Night 2011
Back 2 School Night 2011Back 2 School Night 2011
Back 2 School Night 2011
 
Chapter5
Chapter5Chapter5
Chapter5
 
iPad Apps for Attorneys
iPad Apps for AttorneysiPad Apps for Attorneys
iPad Apps for Attorneys
 
Механизмы адаптации организма к гипоксии
Механизмы адаптации организма к гипоксииМеханизмы адаптации организма к гипоксии
Механизмы адаптации организма к гипоксии
 
District student survey
District student surveyDistrict student survey
District student survey
 
KGI Knauf insulation plafonds (1)
KGI Knauf insulation plafonds (1)KGI Knauf insulation plafonds (1)
KGI Knauf insulation plafonds (1)
 
الفيروسات
الفيروساتالفيروسات
الفيروسات
 
dealomio - or why simple products rule (mobile monday Berlin)
dealomio - or why simple products rule (mobile monday Berlin)dealomio - or why simple products rule (mobile monday Berlin)
dealomio - or why simple products rule (mobile monday Berlin)
 
Основы электрофизиологии
Основы электрофизиологииОсновы электрофизиологии
Основы электрофизиологии
 
PS - sejarah public speaking
PS - sejarah public speakingPS - sejarah public speaking
PS - sejarah public speaking
 
Investment Support Network
Investment Support NetworkInvestment Support Network
Investment Support Network
 
Globalisation 100119101548-phpapp01
Globalisation 100119101548-phpapp01Globalisation 100119101548-phpapp01
Globalisation 100119101548-phpapp01
 
Living with copyright (revised)
Living with copyright (revised)Living with copyright (revised)
Living with copyright (revised)
 
Elastic Intelligence
Elastic IntelligenceElastic Intelligence
Elastic Intelligence
 
Classification of Matter Overview
Classification of Matter OverviewClassification of Matter Overview
Classification of Matter Overview
 
Begin scripting
Begin scriptingBegin scripting
Begin scripting
 
บทที่ 44
บทที่ 44บทที่ 44
บทที่ 44
 

Similar to Symfony2 and MongoDB - MidwestPHP 2013

Introduction to NoSQL with MongoDB
Introduction to NoSQL with MongoDBIntroduction to NoSQL with MongoDB
Introduction to NoSQL with MongoDBHector Correa
 
Deploying Heterogeneous Artifacts to the Cloud with OSGi - Neil Bartlett
Deploying Heterogeneous Artifacts to the Cloud with OSGi - Neil BartlettDeploying Heterogeneous Artifacts to the Cloud with OSGi - Neil Bartlett
Deploying Heterogeneous Artifacts to the Cloud with OSGi - Neil Bartlettmfrancis
 
batou - multi(component|host|environment|.*) deployment
batou - multi(component|host|environment|.*) deploymentbatou - multi(component|host|environment|.*) deployment
batou - multi(component|host|environment|.*) deploymentChristian Theune
 
Basics of Metaprogramming in Ruby
Basics of Metaprogramming in RubyBasics of Metaprogramming in Ruby
Basics of Metaprogramming in RubyDigital Natives
 
Introduction to Twig
Introduction to TwigIntroduction to Twig
Introduction to Twigmarkstory
 
Not Only Drupal
Not Only DrupalNot Only Drupal
Not Only Drupalmcantelon
 
Riak intro to..
Riak intro to..Riak intro to..
Riak intro to..Adron Hall
 
HTML5.tx 2013: Embedded JavaScript, HTML5 and the Internet of Things
HTML5.tx 2013: Embedded JavaScript, HTML5 and the Internet of ThingsHTML5.tx 2013: Embedded JavaScript, HTML5 and the Internet of Things
HTML5.tx 2013: Embedded JavaScript, HTML5 and the Internet of ThingsJesse Cravens
 
Clojure basics
Clojure basicsClojure basics
Clojure basicsKyle Oba
 
Applying Evolutionary Architecture on a Popular API
Applying Evolutionary Architecture on a  Popular APIApplying Evolutionary Architecture on a  Popular API
Applying Evolutionary Architecture on a Popular APIPhil Calçado
 
Mongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeMongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeSpyros Passas
 
Wordpress Plugin Development Practices
Wordpress Plugin Development PracticesWordpress Plugin Development Practices
Wordpress Plugin Development Practicesserversideup
 
Drupal and Apache Stanbol. What if you could reliably do autotagging?
Drupal and Apache Stanbol. What if you could reliably do autotagging?Drupal and Apache Stanbol. What if you could reliably do autotagging?
Drupal and Apache Stanbol. What if you could reliably do autotagging?Gabriel Dragomir
 
Workers of the web - BrazilJS 2013
Workers of the web - BrazilJS 2013Workers of the web - BrazilJS 2013
Workers of the web - BrazilJS 2013Thibault Imbert
 
How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...Oursky
 
How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...Jane Chung
 

Similar to Symfony2 and MongoDB - MidwestPHP 2013 (20)

Caching tips
Caching tipsCaching tips
Caching tips
 
Introduction to NoSQL with MongoDB
Introduction to NoSQL with MongoDBIntroduction to NoSQL with MongoDB
Introduction to NoSQL with MongoDB
 
Rails Intro & Tutorial
Rails Intro & TutorialRails Intro & Tutorial
Rails Intro & Tutorial
 
Deploying Heterogeneous Artifacts to the Cloud with OSGi - Neil Bartlett
Deploying Heterogeneous Artifacts to the Cloud with OSGi - Neil BartlettDeploying Heterogeneous Artifacts to the Cloud with OSGi - Neil Bartlett
Deploying Heterogeneous Artifacts to the Cloud with OSGi - Neil Bartlett
 
batou - multi(component|host|environment|.*) deployment
batou - multi(component|host|environment|.*) deploymentbatou - multi(component|host|environment|.*) deployment
batou - multi(component|host|environment|.*) deployment
 
Basics of Metaprogramming in Ruby
Basics of Metaprogramming in RubyBasics of Metaprogramming in Ruby
Basics of Metaprogramming in Ruby
 
Introduction to Twig
Introduction to TwigIntroduction to Twig
Introduction to Twig
 
Not Only Drupal
Not Only DrupalNot Only Drupal
Not Only Drupal
 
Riak intro to..
Riak intro to..Riak intro to..
Riak intro to..
 
HTML5.tx 2013: Embedded JavaScript, HTML5 and the Internet of Things
HTML5.tx 2013: Embedded JavaScript, HTML5 and the Internet of ThingsHTML5.tx 2013: Embedded JavaScript, HTML5 and the Internet of Things
HTML5.tx 2013: Embedded JavaScript, HTML5 and the Internet of Things
 
What's new in Rails5?
What's new in Rails5?What's new in Rails5?
What's new in Rails5?
 
elasticsearch
elasticsearchelasticsearch
elasticsearch
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Applying Evolutionary Architecture on a Popular API
Applying Evolutionary Architecture on a  Popular APIApplying Evolutionary Architecture on a  Popular API
Applying Evolutionary Architecture on a Popular API
 
Mongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeMongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappe
 
Wordpress Plugin Development Practices
Wordpress Plugin Development PracticesWordpress Plugin Development Practices
Wordpress Plugin Development Practices
 
Drupal and Apache Stanbol. What if you could reliably do autotagging?
Drupal and Apache Stanbol. What if you could reliably do autotagging?Drupal and Apache Stanbol. What if you could reliably do autotagging?
Drupal and Apache Stanbol. What if you could reliably do autotagging?
 
Workers of the web - BrazilJS 2013
Workers of the web - BrazilJS 2013Workers of the web - BrazilJS 2013
Workers of the web - BrazilJS 2013
 
How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...
 
How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...How to write better code: in-depth best practices for writing readable, simpl...
How to write better code: in-depth best practices for writing readable, simpl...
 

More from Pablo Godel

SymfonyCon Cluj 2017 - Symfony at OpenSky
SymfonyCon Cluj 2017 - Symfony at OpenSkySymfonyCon Cluj 2017 - Symfony at OpenSky
SymfonyCon Cluj 2017 - Symfony at OpenSkyPablo Godel
 
Symfony Live San Francisco 2017 - Symfony @ OpenSky
Symfony Live San Francisco 2017 - Symfony @ OpenSkySymfony Live San Francisco 2017 - Symfony @ OpenSky
Symfony Live San Francisco 2017 - Symfony @ OpenSkyPablo Godel
 
DeSymfony 2017 - Symfony en OpenSky
DeSymfony 2017 - Symfony en OpenSkyDeSymfony 2017 - Symfony en OpenSky
DeSymfony 2017 - Symfony en OpenSkyPablo Godel
 
Deploying Symfony | symfony.cat
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.catPablo Godel
 
SymfonyCon Madrid 2014 - Rock Solid Deployment of Symfony Apps
SymfonyCon Madrid 2014 - Rock Solid Deployment of Symfony AppsSymfonyCon Madrid 2014 - Rock Solid Deployment of Symfony Apps
SymfonyCon Madrid 2014 - Rock Solid Deployment of Symfony AppsPablo Godel
 
La Caja de Herramientas del Desarrollador Moderno PHPConferenceAR
La Caja de Herramientas del Desarrollador Moderno PHPConferenceARLa Caja de Herramientas del Desarrollador Moderno PHPConferenceAR
La Caja de Herramientas del Desarrollador Moderno PHPConferenceARPablo Godel
 
Symfony Live NYC 2014 - Rock Solid Deployment of Symfony Apps
Symfony Live NYC 2014 -  Rock Solid Deployment of Symfony AppsSymfony Live NYC 2014 -  Rock Solid Deployment of Symfony Apps
Symfony Live NYC 2014 - Rock Solid Deployment of Symfony AppsPablo Godel
 
The Modern Developer Toolbox
The Modern Developer ToolboxThe Modern Developer Toolbox
The Modern Developer ToolboxPablo Godel
 
PHP Conference Argentina 2013 - Independizate de tu departamento IT - Habilid...
PHP Conference Argentina 2013 - Independizate de tu departamento IT - Habilid...PHP Conference Argentina 2013 - Independizate de tu departamento IT - Habilid...
PHP Conference Argentina 2013 - Independizate de tu departamento IT - Habilid...Pablo Godel
 
PHP Conference Argentina 2013 - Deployment de aplicaciones PHP a prueba de balas
PHP Conference Argentina 2013 - Deployment de aplicaciones PHP a prueba de balasPHP Conference Argentina 2013 - Deployment de aplicaciones PHP a prueba de balas
PHP Conference Argentina 2013 - Deployment de aplicaciones PHP a prueba de balasPablo Godel
 
php[architect] Summit Series DevOps 2013 - Rock solid deployment of PHP apps
php[architect] Summit Series DevOps 2013 - Rock solid deployment of PHP appsphp[architect] Summit Series DevOps 2013 - Rock solid deployment of PHP apps
php[architect] Summit Series DevOps 2013 - Rock solid deployment of PHP appsPablo Godel
 
Lone Star PHP 2013 - Sysadmin Skills for PHP Developers
Lone Star PHP 2013 - Sysadmin Skills for PHP DevelopersLone Star PHP 2013 - Sysadmin Skills for PHP Developers
Lone Star PHP 2013 - Sysadmin Skills for PHP DevelopersPablo Godel
 
Lone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New AngleLone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New AnglePablo Godel
 
deSymfony 2013 - Creando aplicaciones web desde otro ángulo con Symfony y A...
deSymfony 2013 -  Creando aplicaciones web desde otro ángulo con Symfony y A...deSymfony 2013 -  Creando aplicaciones web desde otro ángulo con Symfony y A...
deSymfony 2013 - Creando aplicaciones web desde otro ángulo con Symfony y A...Pablo Godel
 
Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2Pablo Godel
 
Tek13 - Creating Mobile Apps with PHP and Symfony
Tek13 - Creating Mobile Apps with PHP and SymfonyTek13 - Creating Mobile Apps with PHP and Symfony
Tek13 - Creating Mobile Apps with PHP and SymfonyPablo Godel
 
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJSTek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJSPablo Godel
 
Soflophp 2013 - SysAdmin skills for PHP developers
Soflophp 2013 - SysAdmin skills for PHP developersSoflophp 2013 - SysAdmin skills for PHP developers
Soflophp 2013 - SysAdmin skills for PHP developersPablo Godel
 
Rock Solid Deployment of Web Applications
Rock Solid Deployment of Web ApplicationsRock Solid Deployment of Web Applications
Rock Solid Deployment of Web ApplicationsPablo Godel
 
Codeworks'12 Rock Solid Deployment of PHP Apps
Codeworks'12 Rock Solid Deployment of PHP AppsCodeworks'12 Rock Solid Deployment of PHP Apps
Codeworks'12 Rock Solid Deployment of PHP AppsPablo Godel
 

More from Pablo Godel (20)

SymfonyCon Cluj 2017 - Symfony at OpenSky
SymfonyCon Cluj 2017 - Symfony at OpenSkySymfonyCon Cluj 2017 - Symfony at OpenSky
SymfonyCon Cluj 2017 - Symfony at OpenSky
 
Symfony Live San Francisco 2017 - Symfony @ OpenSky
Symfony Live San Francisco 2017 - Symfony @ OpenSkySymfony Live San Francisco 2017 - Symfony @ OpenSky
Symfony Live San Francisco 2017 - Symfony @ OpenSky
 
DeSymfony 2017 - Symfony en OpenSky
DeSymfony 2017 - Symfony en OpenSkyDeSymfony 2017 - Symfony en OpenSky
DeSymfony 2017 - Symfony en OpenSky
 
Deploying Symfony | symfony.cat
Deploying Symfony | symfony.catDeploying Symfony | symfony.cat
Deploying Symfony | symfony.cat
 
SymfonyCon Madrid 2014 - Rock Solid Deployment of Symfony Apps
SymfonyCon Madrid 2014 - Rock Solid Deployment of Symfony AppsSymfonyCon Madrid 2014 - Rock Solid Deployment of Symfony Apps
SymfonyCon Madrid 2014 - Rock Solid Deployment of Symfony Apps
 
La Caja de Herramientas del Desarrollador Moderno PHPConferenceAR
La Caja de Herramientas del Desarrollador Moderno PHPConferenceARLa Caja de Herramientas del Desarrollador Moderno PHPConferenceAR
La Caja de Herramientas del Desarrollador Moderno PHPConferenceAR
 
Symfony Live NYC 2014 - Rock Solid Deployment of Symfony Apps
Symfony Live NYC 2014 -  Rock Solid Deployment of Symfony AppsSymfony Live NYC 2014 -  Rock Solid Deployment of Symfony Apps
Symfony Live NYC 2014 - Rock Solid Deployment of Symfony Apps
 
The Modern Developer Toolbox
The Modern Developer ToolboxThe Modern Developer Toolbox
The Modern Developer Toolbox
 
PHP Conference Argentina 2013 - Independizate de tu departamento IT - Habilid...
PHP Conference Argentina 2013 - Independizate de tu departamento IT - Habilid...PHP Conference Argentina 2013 - Independizate de tu departamento IT - Habilid...
PHP Conference Argentina 2013 - Independizate de tu departamento IT - Habilid...
 
PHP Conference Argentina 2013 - Deployment de aplicaciones PHP a prueba de balas
PHP Conference Argentina 2013 - Deployment de aplicaciones PHP a prueba de balasPHP Conference Argentina 2013 - Deployment de aplicaciones PHP a prueba de balas
PHP Conference Argentina 2013 - Deployment de aplicaciones PHP a prueba de balas
 
php[architect] Summit Series DevOps 2013 - Rock solid deployment of PHP apps
php[architect] Summit Series DevOps 2013 - Rock solid deployment of PHP appsphp[architect] Summit Series DevOps 2013 - Rock solid deployment of PHP apps
php[architect] Summit Series DevOps 2013 - Rock solid deployment of PHP apps
 
Lone Star PHP 2013 - Sysadmin Skills for PHP Developers
Lone Star PHP 2013 - Sysadmin Skills for PHP DevelopersLone Star PHP 2013 - Sysadmin Skills for PHP Developers
Lone Star PHP 2013 - Sysadmin Skills for PHP Developers
 
Lone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New AngleLone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New Angle
 
deSymfony 2013 - Creando aplicaciones web desde otro ángulo con Symfony y A...
deSymfony 2013 -  Creando aplicaciones web desde otro ángulo con Symfony y A...deSymfony 2013 -  Creando aplicaciones web desde otro ángulo con Symfony y A...
deSymfony 2013 - Creando aplicaciones web desde otro ángulo con Symfony y A...
 
Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2Creating Mobile Apps With PHP & Symfony2
Creating Mobile Apps With PHP & Symfony2
 
Tek13 - Creating Mobile Apps with PHP and Symfony
Tek13 - Creating Mobile Apps with PHP and SymfonyTek13 - Creating Mobile Apps with PHP and Symfony
Tek13 - Creating Mobile Apps with PHP and Symfony
 
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJSTek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJS
 
Soflophp 2013 - SysAdmin skills for PHP developers
Soflophp 2013 - SysAdmin skills for PHP developersSoflophp 2013 - SysAdmin skills for PHP developers
Soflophp 2013 - SysAdmin skills for PHP developers
 
Rock Solid Deployment of Web Applications
Rock Solid Deployment of Web ApplicationsRock Solid Deployment of Web Applications
Rock Solid Deployment of Web Applications
 
Codeworks'12 Rock Solid Deployment of PHP Apps
Codeworks'12 Rock Solid Deployment of PHP AppsCodeworks'12 Rock Solid Deployment of PHP Apps
Codeworks'12 Rock Solid Deployment of PHP Apps
 

Recently uploaded

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 

Recently uploaded (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 

Symfony2 and MongoDB - MidwestPHP 2013

  • 1. Pablo Godel @pgodel - MidwestPHP 2013 March 2nd 2013 - St. Paul, MN https://joind.in/8211 Sunday, March 3, 13
  • 2. Who Am I? ⁃ Born in Argentina, living in the US since 1999 ⁃ PHP & Symfony developer ⁃ Founder of the original PHP mailing list in spanish ⁃ Master of the parrilla Sunday, March 3, 13
  • 5. ServerGrove! ⁃ Founded ServerGrove Networks in 2005 ⁃ Provider of web hosting specialized in PHP, Symfony, ZendFramework, and others ⁃ Mongohosting.com! ⁃ Servers in Miami, FL and Dublin, Ireland Sunday, March 3, 13
  • 6. Community is our teacher ⁃ Very active open source supporter through code contributions and usergroups/conference sponsoring Sunday, March 3, 13
  • 7. Agenda - Introduction to MongoDB - PHP and MongoDB - PHP Libraries - Introduction to Symfony2 - Symfony2 and MongoDB Sunday, March 3, 13
  • 8. What is MongoDB? Who is 10Gen? Sunday, March 3, 13
  • 9. Mongo Mongo as in "humongous". Used to describe something extremely large or important. Sunday, March 3, 13
  • 10. MongoDB is a scalable, high-performance, open source NoSQL database. - Document Oriented DB - Written in C++ - Available for *nux (Linux, Solaris, etc), Windows and OS X - Lots of Drivers (PHP, Java, Python, Ruby...) Sunday, March 3, 13
  • 11. Features - Flexible JSON-style documents - Full Indexing - Complex Queries / Map Reduce - Aggregation Framework - GridFS (store files natively) - Multiple Replication Options - Sharding - Simple Installation / Zero Config Sunday, March 3, 13
  • 12. Document Oriented Coming from SQL? Database => Database Table => Collection Row => Document Sunday, March 3, 13
  • 13. JSON-style documents { name: { first: 'John', last: 'Doe' }, title: 'Engineer', age: 40 } Sunday, March 3, 13
  • 14. No Schema or fixed tables { name: { first: 'Foo', last: 'Bar' }, title: 'Student', school: 'Harvard' } Sunday, March 3, 13
  • 15. Embedded documents { "_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" } ] } } Sunday, March 3, 13
  • 16. Document Referencing { "_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") } ] } Sunday, March 3, 13
  • 17. Full Indexing db.coll.ensureIndex({name.last: 1}) db.coll.ensureIndex({name.first: 1, name.last: 1}) db.coll.ensureIndex({age: 0}) Sunday, March 3, 13
  • 18. Querying db.coll.find({name: 'John'}) db.coll.find({keywords: 'storage'}) db.coll.find({keywords: {$in: ['storage', 'DBMS']}} Sunday, March 3, 13
  • 19. GridFS - Files are divided in chunks and stored over multiple documents - Transparent API $grid->storeFile("/path/to/somefile.txt",  array("metadata" => array("date" => new MongoDate()))); Sunday, March 3, 13
  • 20. Replication Source: http://www.mongodb.org/display/DOCS/Replication Sunday, March 3, 13
  • 21. Shards Source: http://www.mongodb.org/display/DOCS/Introduction Sunday, March 3, 13
  • 22. Simple Installation/Zero Config OS X wget http://fastdl.mongodb.org/osx/mongodb-osx-x86_64-2.2.3.tgz tar zxvf mongodb-osx-x86_64-2.2.3.tgz cd mongodb-osx-x86_64-2.2.3 ./mongod Sunday, March 3, 13
  • 23. Simple Installation/Zero Config 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-10gen-server $ service mongod start Sunday, March 3, 13
  • 24. Why is MongoDB good for Rapid Development of Web Apps? Sunday, March 3, 13
  • 25. Rapid Development Schema-less / Document Oriented FLEXIBILITY by exfordy Sunday, March 3, 13
  • 26. Rapid Development Schema-less / Document Oriented EASIER MIGRATIONS by exfordy Sunday, March 3, 13
  • 27. Rapid Development NO JOINS! Sunday, March 3, 13
  • 28. Performance SPEED by xavi talleda Sunday, March 3, 13
  • 29. Performance SCALABILITY by Jimee, Jackie, Tom & Asha Sunday, March 3, 13
  • 30. A Word of Caution No Transactions No Rollbacks Unsafe defaults Map Reduce locks by Ernst Vikne Sunday, March 3, 13
  • 31. Great Use Cases - Content Management - Product Catalogs - Realtime Analytics - Logs Storage Sunday, March 3, 13
  • 33. PECL driver 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/downloads Sunday, March 3, 13
  • 34. Attention Mongo 1.2.x $m = new Mongo(); Mongo 1.3.x $m = new MongoClient(); Sunday, March 3, 13
  • 35. Usage <?php // connect $m = new MongoClient(); // select a database $db = $m->comedy; // select a collection (analogous to a relational database's table) $collection = $db->cartoons; // add a record $obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watte rson" ); $collection->insert($obj); // add another record, with a different "shape" $obj = array( "title" => "XKCD", "online" => true ); $collection->insert($obj); // find everything in the collection $cursor = $collection->find(); // iterate through the results foreach ($cursor as $obj) {     echo $obj["title"] . "n"; } ?> Sunday, March 3, 13
  • 36. Storing Files <?php // save a file $id = $grid->storeFile("game.tgz"); $game = $grid->findOne(); // add a downloads counter $game->file['downloads'] = 0; $grid->save($game->file); // increment the counter $grid- >update(array("_id" => $id), array('$inc' => array("downloads " => 1))); ?> Sunday, March 3, 13
  • 37. SQL to Mongo Queries SQL to Mongo Mapping Chart This is a PHP-specific version of the » SQL to Mongo mapping chart in the main docs. SQL Statement Mongo Query Language Statement CREATE TABLE USERS (a Number, b Number) Implicit or use MongoDB::createCollection(). INSERT INTO USERS VALUES(1,1) $db->users->insert(array("a" => 1, "b" => 1)); SELECT a,b FROM users $db->users->find(array(), array("a" => 1, "b" => 1)); SELECT * FROM users WHERE age=33 $db->users->find(array("age" => 33)); SELECT a,b FROM users WHERE age=33 $db->users->find(array("age" => 33), array("a" => 1, "b" => 1)); SELECT a,b FROM users WHERE age=33 ORDER BY name $db->users->find(array("age" => 33), array("a" => 1, "b" => 1))->sort(array("name" => 1)); SELECT * FROM users WHERE age>33 $db->users->find(array("age" => array('$gt' => 33))); SELECT * FROM users WHERE age<33 $db->users->find(array("age" => array('$lt' => 33))); SELECT * FROM users WHERE name LIKE "%Joe%" $db->users->find(array("name" => new MongoRegex("/Joe/"))); SELECT * FROM users WHERE name LIKE "Joe%" $db->users->find(array("name" => new MongoRegex("/^Joe/"))); SELECT * FROM users WHERE age>33 AND age<=40 $db->users->find(array("age" => array('$gt' => 33, '$lte' => 40))); SELECT * FROM users ORDER BY name DESC http://php.net/manual/en/ mongo.sqltomongo.php Sunday, March 3, 13
  • 38. Admin Interfaces - Genghis http://genghisapp.com/ - RockMongo http://code.google.com/p/rock-php/wiki/rock_mongo - php-mongodb-admin https://github.com/jwage/php-mongodb-admin Sunday, March 3, 13
  • 39. PHP Libraries - Doctrine ODM Doctrine MongoDB Object Document Mapper is built for PHP 5.3.2+ and provides transparent persistence for PHP objects. - Mandango Mandango is a simple, poweful and ultrafast Object Document Mapper (ODM) for PHP and MongoDB. - many more... Sunday, March 3, 13
  • 40. Doctrine MongoDB ODM http://doctrine-project.org Doctrine MongoDB Object Document Mapper is built for PHP 5.3.2+ and provides transparent persistence for PHP objects. Sunday, March 3, 13
  • 41. Doctrine MongoDB ODM /** @Document */ class User { /** @Id */ private $id; /** @String */ private $name; /** @String */ private $email; /** @ReferenceMany(targetDocument="BlogPost", cascade="all") */ private $posts; // ... } Sunday, March 3, 13
  • 42. Doctrine MongoDB ODM /** @Document */ class BlogPost { /** @Id */ private $id; /** @String */ private $title; /** @String */ private $body; /** @Date */ private $createdAt; // ... } Sunday, March 3, 13
  • 43. Doctrine MongoDB ODM <?php // create user $user = new User(); $user->setName('Bulat S.'); $user->setEmail('email@example.com'); // tell Doctrine 2 to save $user on the next flush() $dm->persist($user); // create blog post $post = new BlogPost(); $post->setTitle('My First Blog Post'); $post->setBody('MongoDB + Doctrine 2 ODM = awesomeness!'); $post->setCreatedAt(new DateTime()); $user->addPost($post); // store everything to MongoDB $dm->flush(); Sunday, March 3, 13
  • 44. Doctrine MongoDB ODM Array ( [_id] => 4bec5869fdc212081d000000 [title] => My First Blog Post [body] => MongoDB + Doctrine 2 ODM = awesomeness! [createdAt] => MongoDate Object ( [sec] => 1273723200 [usec] => 0 ) ) Sunday, March 3, 13
  • 45. Doctrine MongoDB ODM Array ( [_id] => 4bec5869fdc212081d010000 [name] => Bulat S. [email] => email@example.com [posts] => Array ( [0] => Array ( [$ref] => blog_posts [$id] => 4bec5869fdc212081d000000 [$db] => test_database ) ) ) Sunday, March 3, 13
  • 46. Doctrine MongoDB ODM Retrieving Persisted Objects $user = $dm->find('User', $userId); $user = $dm->getRepository('User')->findOneByName('Bulat S.'); $posts = $user->getPosts(); foreach ($posts as $post) { echo $post; } Sunday, March 3, 13
  • 47. Doctrine MongoDB ODM Document Repositories // src/YourNamespace/YourBundle/ServerRepository.php namespace YourNamespaceYourBundle; 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(‘@YourBundle/Server’); $servers = $rep->getActiveServers(); Sunday, March 3, 13
  • 48. Doctrine MongoDB ODM /** @Document */ class Image { /** @Id */ private $id; /** @Field */ private $name; /** @File */ private $file; Sunday, March 3, 13
  • 49. Doctrine MongoDB ODM // store file $image = new Image(); $image->setName('Test image'); $image->setFile('/path/to/image.png'); $dm->persist($image); $dm->flush(); // retrieve and return file to client $image = $dm->createQueryBuilder('DocumentsImage') ->field('name')->equals('Test image') ->getQuery() ->getSingleResult(); header('Content-type: image/png;'); echo $image->getFile()->getBytes(); Sunday, March 3, 13
  • 50. Tips: Doctrine MongoDB ODM // Eager ID creation public function __construct() { $this->id = (string) new MongoId(); } Sunday, March 3, 13
  • 51. Tips: Doctrine MongoDB ODM // Creation date public function __construct() { $this->id = (string) new MongoId(); $this->createdDt = new DateTime(); } Sunday, March 3, 13
  • 52. Tips: Doctrine MongoDB ODM // ArrayCollections public function __construct() { $this->id = (string) new MongoId(); $this->createdDt = new DateTime(); $this->entries = new ArrayCollection(); } Sunday, March 3, 13
  • 53. Tips: Doctrine MongoDB ODM // Space Saving /** @String(name=”n”) */ private $name; /** @String(name=”e”) */ private $email; Sunday, March 3, 13
  • 54. Symfony is a PHP Web Development Framework. Sunday, March 3, 13
  • 55. “First, Symfony2 is a reusable set of standalone, decoupled, and cohesive PHP components that solve common web development problems. Then, based on these components, Symfony2 is also a full-stack web framework.” http://fabien.potencier.org/article/49/what-is-symfony2 Sunday, March 3, 13
  • 56. 25 High Quality Components Sunday, March 3, 13
  • 57. Symfony 2 Components • DependencyInjection • Serializer • EventDispatcher • Validator • HttpFoundation • Security • DomCrawler • Routing • ClassLoader • Console • CssSelector • Process • HttpKernel • Config • BrowserKit • Finder • Templating • Locale • Translation • Yaml • Serializer • Form • More... All of them at GitHub: http://github.com/symfony Sunday, March 3, 13
  • 58. Symfony 2 Components Components Documentation http://symfony.com/doc/current/components/index.html Blog post series about creating a framework based on the Symfony2 Components http://fabien.potencier.org/ Sunday, March 3, 13
  • 59. Symfony 2 Highlights • Rewritten from scratch for PHP 5.3 • Based on the HTTP specification • Very stable and solid API • Extensible through the creation of Bundles (replacement for sf1 plugins) • Flexible configuration using YAML, XML, annotations or PHP • All configuration is compiled to PHP code and cached • Lots of unit tests • Source code audited by independent security firm thanks to donations of the Symfony Community Sunday, March 3, 13
  • 60. Symfony 2 Highlights • Extensible Configuration with Service Container/ Dependency Injection • Complete redesign of Forms support • Validations • Extensible Security with Authentication/Authorization • Advanced and powerful templating through Twig • Routes configured with YAML, XML or Annotations • ESI Caching support out of the box • Assets management with Assetic • Translations • Environments Sunday, March 3, 13
  • 61. Symfony 2 Highlights: Community • 698 developers contributed to Symfony2 • 7000+ pull requests • 969 1901 bundles at knpbundles.com • Very active IRC and mailing lists support channels • Community Gamification through SensioLabs Connect • Symfony2 Ecosystem Sunday, March 3, 13
  • 62. Symfony 2 Highlights: Bundles Sunday, March 3, 13
  • 63. Symfony 2 Getting Started http://symfony.com/download Sunday, March 3, 13
  • 64. Symfony 2 Getting Started tar zxf Symfony_Standard_Vendors_2.2.0.tgz or unzip Symfony_Standard_Vendors_2.2.0.zip Sunday, March 3, 13
  • 65. Symfony 2 Getting Started with Composer $ curl -s https://getcomposer.org/installer | php $ php composer.phar create-project symfony/framework-standard-edition path/ 2.2.0 http://getcomposer.org/ Sunday, March 3, 13
  • 66. Symfony 2 Getting Started Distributions A Symfony distribution is made up of Symfony2 components, a selection of bundles, a directory structure, a default configuration. http://symfony.com/distributions Sunday, March 3, 13
  • 67. Symfony 2 Getting Started Symfony Standard Distribution • Directory structure • Default configuration • Bundles ⁃ DoctrineBundle ⁃ JMSSecurityExtraBundle ⁃ SensioDistributionBundle ⁃ SensioFrameworkExtraBundle ⁃ SensioGeneratorBundle ⁃ AsseticBundle http://symfony.com/distributions Sunday, March 3, 13
  • 68. Symfony 2 Getting Started Sunday, March 3, 13
  • 69. Symfony 2 Getting Started Sunday, March 3, 13
  • 70. Symfony 2 Directory Structure Sunday, March 3, 13
  • 71. Symfony 2 Directory Structure Sunday, March 3, 13
  • 72. Symfony 2 Directory Structure Sunday, March 3, 13
  • 73. Symfony 2 Directory Structure Sunday, March 3, 13
  • 74. Symfony 2 Configuration: app/config.yml Sunday, March 3, 13
  • 75. Symfony 2 Configuration: app/parameters.ini Sunday, March 3, 13
  • 76. Symfony 2 Configuration: app/config_dev.yml Sunday, March 3, 13
  • 77. Browser Request Bootstrap (app.php) Controller Template Response Want to know more? Go to Raul Fraile’s Symfony2 Internals Talk Sunday, March 3, 13
  • 79. Symfony 2 Bootstrap File - web/app.php Sunday, March 3, 13
  • 85. Symfony 2 Templating / Twig Comments: {# comments are not rendered #} {# multi-line comments! {{ var }} #} Output variables: {{ var }} {{ var | upper }} {{ var | raw }} {{ object.property }} {{ true ? ‘yes’ : ‘no’ }} http://twig.sensiolabs.org/ Sunday, March 3, 13
  • 86. Symfony 2 Templating / Twig Blocks: {% set var = ‘hello’ %} {% set foo = var ~ ’ and goodbye’ %} {% if foo is ‘bar’ %} ... {% else %} ... {% endif %} http://twig.sensiolabs.org/ Sunday, March 3, 13
  • 87. Symfony 2 Templating / Twig Blocks: {% for key, val in list %} {{ loop.index }}. {{ val }} {% else %} No keys. {% endfor %} http://twig.sensiolabs.org/ Sunday, March 3, 13
  • 88. Symfony 2 Templating / Twig Extends: {% extends "Bundle::layout.html.twig" %} Include: {% include “Bundle:Demo:template.html.twig” %} Render: {% render “Bundle:Demo:action” %} http://twig.sensiolabs.org/ Sunday, March 3, 13
  • 89. Awesome Twig Presentations Twig, The Flexible, Fast and Secure Template Language for PHP - Fabien Potencier http://www.slideshare.net/fabpot/twig-the-flexible-fast-and-securetemplate- language-for-php Being Dangerous with Twig - Ryan Weaver http://slideshare.net/weaverryan/being-dangerous-with-twig-symfony- live-paris Twig avanzado - Javier Eguiluz http://www.slideshare.net/javier.eguiluz/twig-avanzado-sf2vigo (Spanish) Sunday, March 3, 13
  • 94. Symfony 2 Bundles Everything in Symfony2 is contained in Bundles Sunday, March 3, 13
  • 95. Symfony 2 Bundles Even Symfony2 is a collection of Bundles Sunday, March 3, 13
  • 96. Symfony 2 Directory Structure Sunday, March 3, 13
  • 97. Symfony 2 Bundles Registration app/AppKernel.php Sunday, March 3, 13
  • 98. Symfony 2 Bundles for MongoDB - DoctrineMongoDBBundle - MandangoBundle Sunday, March 3, 13
  • 99. Symfony 2 Installing DoctrineMongoDBBundle Installation with Composer composer.json { require": { "doctrine/mongodb-odm-bundle": "3.0.*" }, "minimum-stability": "dev" } $ php composer.phar update $ php composer.phar install doctrine/mongodb-odm-bundle Sunday, March 3, 13
  • 100. Symfony 2 Installing DoctrineMongoDBBundle Installation with Composer $ php composer.phar require doctrine/mongodb-odm-bundle:3.0.* Sunday, March 3, 13
  • 101. Symfony 2 Configuring DoctrineMongoDBBundle app/autoload.php // app/autoload.php use DoctrineODMMongoDBMappingDriverAnnotationDriver; AnnotationDriver::registerAnnotationClasses(); Sunday, March 3, 13
  • 102. Symfony 2 Configuring DoctrineMongoDBBundle app/config/config.yml doctrine_mongodb: connections: default: server: mongodb://localhost:27017 options: connect: true default_database: test_database document_managers: default: auto_mapping: true Sunday, March 3, 13
  • 103. Symfony 2 Multiple Connections & Bundle Mappings 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 MyBundle: { type: xml, dir: Resources/config/doctrine/ mapping } Sunday, March 3, 13
  • 104. Symfony 2 Defining Documents Sunday, March 3, 13
  • 105. Symfony 2 Defining Documents // 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; Sunday, March 3, 13
  • 106. Symfony 2 Using Documents // 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_mongodb')->getManager(); $dm->persist($product); $dm->flush(); return new Response('Created product id '.$product->getId()); } Sunday, March 3, 13
  • 107. Symfony 2 Forms Since Documents are Plain PHP Objects integrating it with Symfony Forms is straightforward. public function createAction() { $dm = $this->get('doctrine_mongodb')->getManager(); $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.html Sunday, March 3, 13
  • 108. Symfony 2 ODM Commands Symfony2 Commands 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 documents Sunday, March 3, 13
  • 109. TIP: Storing Symfony Sessions in MongoDB app/config/config.yml Sunday, March 3, 13
  • 110. TIP: Mixing Doctrine ODM & ORM Order Product Entity (ORM) Document (ODM) http://docs.doctrine-project.org/projects/doctrine- mongodb-odm/en/latest/cookbook/blending-orm-and- mongodb-odm.html Sunday, March 3, 13
  • 111. TIP: Persisting objects with ODM or ORM <?php namespace DoctrineBlog; /** @Entity(repositoryClass="DoctrineBlogORMBlogPostRepository") */ class BlogPost { /** @Id @Column(type="integer") */ private $id; /** @Column(type="string") */ private $title; /** @Column(type="text") */ private $body; // ... } Sunday, March 3, 13
  • 112. TIP: Persisting objects with ODM or ORM <?php namespace Documents; /** @Document(repositoryClass="DoctrineBlogODMMongoDB BlogPostRepository") */ class BlogPost { /** @Id */ private $id; /** @Field(type="string") */ private $title; /** @Field(type="string") */ private $body; // ... } Sunday, March 3, 13
  • 113. Symfony 2 Bundles using MongoDB - SonataDoctrineMongoDBAdminBundle - IsmaAmbrosiGeneratorBundle - TranslationEditorBundle - ServerGroveLiveChat Sunday, March 3, 13
  • 114. Additional Resources - http://php.net/mongo - http://docs.mongodb.org/manual/ - http://symfony.com/doc/current/index.html - http://www.doctrine-project.org/docs/mongodb-odm Sunday, March 3, 13
  • 116. Thank you! Rate Me Please! https://joind.in/8211 Slides: http://slideshare.net/pgodel Twitter: @pgodel E-mail: pablo@servergrove.com Sunday, March 3, 13