See how to use MongoDB in Symfony2 projects to speed up the development of web applications. We will give an introduction of MongoDB as a NoSQL database server and look at the options on how to work with it from Symfony2 and PHP applications.
Scanning the Internet for External Cloud Exposures via SSL Certs
Symfony2 and MongoDB
1. Pablo Godel @pgodel - 2012.phpDay.it
May 18th 2012 - Verona, Italy
https://joind.in/6383
Friday, May 18, 2012
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
Friday, May 18, 2012
3. 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
Friday, May 18, 2012
5. ServerGrove!
⁃ Founded ServerGrove Networks in 2005
⁃ Provider of web hosting specialized in PHP,
Symfony, ZendFramework, and others
⁃ Mongohosting.com under beta!
Friday, May 18, 2012
6. Community is our teacher
⁃ Very active open source supporter through code
contributions and usergroups/conference sponsoring
Friday, May 18, 2012
7. Agenda
- Introduction to MongoDB
- PHP and MongoDB
- PHP Libraries
- Symfony2 and MongoDB
Friday, May 18, 2012
9. Mongo
Mongo as in "humongous". Used to describe
something extremely large or important.
Friday, May 18, 2012
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...)
Friday, May 18, 2012
19. GridFS
- Files are divided in chunks
and stored over multiple documents
- Transparent API
Friday, May 18, 2012
20. Replication
Source: http://www.mongodb.org/display/DOCS/Replication
Friday, May 18, 2012
21. Shards
Source: http://www.mongodb.org/display/DOCS/Introduction
Friday, May 18, 2012
22. Simple Installation/Zero Config
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
./mongod
Friday, May 18, 2012
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-stable-server
$ service mongod start
Friday, May 18, 2012
24. Why is MongoDB good for Rapid
Development of Web Apps?
Friday, May 18, 2012
25. Rapid Development
Schema-less / Document Oriented
FLEXIBILITY
by exfordy
Friday, May 18, 2012
26. Rapid Development
Schema-less / Document Oriented
EASIER
MIGRATIONS
by exfordy
Friday, May 18, 2012
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
Friday, May 18, 2012
34. Usage
<?php
// connect
$m = new Mongo();
// 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 Watterson" );
$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";
}
?>
Friday, May 18, 2012
35. 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)));
?>
Friday, May 18, 2012
36. 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
Friday, May 18, 2012
38. PHP Libraries
- Doctrine ODM
- Mandango
- many more...
Friday, May 18, 2012
39. 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.
Friday, May 18, 2012
42. 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();
Friday, May 18, 2012
43. Doctrine MongoDB ODM
Array
(
[_id] => 4bec5869fdc212081d000000
[title] => My First Blog Post
[body] => MongoDB + Doctrine 2 ODM = awesomeness!
[createdAt] => MongoDate Object
(
[sec] => 1273723200
[usec] => 0
)
)
Friday, May 18, 2012
56. DoctrineMongoDBBundle
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;
Friday, May 18, 2012
57. DoctrineMongoDBBundle
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.odm.mongodb.document_manager');
$dm->persist($product);
$dm->flush();
return new Response('Created product id '.$product->getId());
}
Friday, May 18, 2012
58. Forms
Since Documents are Plain PHP Objects integrating it with Symfony Forms is straightforward.
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.html
Friday, May 18, 2012
59. 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
Friday, May 18, 2012
60. Bundles using MongoDB
- SonataDoctrineMongoDBAdminBundle
- IsmaAmbrosiGeneratorBundle
- EbutikMongoSessionBundle
- TranslationEditorBundle
- ServerGroveLiveChat
Friday, May 18, 2012