MongoDB + Java - Everything you need to know Norberto Leite
Learn everything you need to know to get started building a MongoDB-based app in Java. We'll explore the relationship between MongoDB and various languages on the Java Virtual Machine such as Java, Scala, and Clojure. From there, we'll examine the popular frameworks and integration points between MongoDB and the JVM including Spring Data and object-document mappers like Morphia.
PHP Data Objects (PDO) provides a clear, simple (but powerful), unified API for working with all our favorite databases. Features include prepared statements with bound parameters (for all databases, even those that don’t natively support them), transactions, cursors, LOBs, and flexible error handling.
MongoDB + Java - Everything you need to know Norberto Leite
Learn everything you need to know to get started building a MongoDB-based app in Java. We'll explore the relationship between MongoDB and various languages on the Java Virtual Machine such as Java, Scala, and Clojure. From there, we'll examine the popular frameworks and integration points between MongoDB and the JVM including Spring Data and object-document mappers like Morphia.
PHP Data Objects (PDO) provides a clear, simple (but powerful), unified API for working with all our favorite databases. Features include prepared statements with bound parameters (for all databases, even those that don’t natively support them), transactions, cursors, LOBs, and flexible error handling.
PHP 5.3 and Lithium: the most rad php frameworkG Woo
Presentation given to the Orange County PHP meetup on Feb 24 2010. The presentation covers the new features in php 5.3 and goes on to show how they are used in Lithium, the most rad php framework.
Webinar: MongoDB Persistence with Java and MorphiaMongoDB
MongoDB is the leading noSQL database and as with any new technology, some of the biggest questions are about tools and integration. This webinar will cover how to use MongoDB from a Java application and introduce Morphia, the object document mapping library. It will cover the essential features of the framework with examples before moving on to some of the more advanced and upcoming features such as text search and aggregation framework support.
Persistence is one of the most important part in a PHP project. Persisting data to a database came with PHP/FI and its MySQL support. From native extensions and PHP4 database abstraction libraries to PDO and modern ORM frameworks, you will (re)discover how persistence has evolved during the last decade. This talk will also introduce the future of data persistence with the growing success of alternative storage engines.
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
Cette conférence présente deux grands motifs de conception : l'observateur et l'injection de dépendance. Ce sujet allie à la fois théorie et pratique. Le composant autonome EventDispatcher de Symfony ainsi que le conteneur d'injection de dépendance Pimple sont mis à l'honneur avec des exemples pratiques d'usage. Ces cas pratiques combinent du code de l'ORM Propel ainsi que le composant autonome Zend\Search\Lucene du Zend Framework 2
The recent Project of the Month on SourceForge, XOOPS (http://www.xoops.org) was designed from the very beginning as an object-oriented CMS, which is even reflected in its name: eXtensible Object Oriented Portal System. Michael will present the OOP oriented architecture of XOOPS, and show how OOP makes development of XOOPS modules easy and fun, promotes reuse of code, while keeping GUI consistent across all modules.
PHP 5.3 and Lithium: the most rad php frameworkG Woo
Presentation given to the Orange County PHP meetup on Feb 24 2010. The presentation covers the new features in php 5.3 and goes on to show how they are used in Lithium, the most rad php framework.
Webinar: MongoDB Persistence with Java and MorphiaMongoDB
MongoDB is the leading noSQL database and as with any new technology, some of the biggest questions are about tools and integration. This webinar will cover how to use MongoDB from a Java application and introduce Morphia, the object document mapping library. It will cover the essential features of the framework with examples before moving on to some of the more advanced and upcoming features such as text search and aggregation framework support.
Persistence is one of the most important part in a PHP project. Persisting data to a database came with PHP/FI and its MySQL support. From native extensions and PHP4 database abstraction libraries to PDO and modern ORM frameworks, you will (re)discover how persistence has evolved during the last decade. This talk will also introduce the future of data persistence with the growing success of alternative storage engines.
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
Cette conférence présente deux grands motifs de conception : l'observateur et l'injection de dépendance. Ce sujet allie à la fois théorie et pratique. Le composant autonome EventDispatcher de Symfony ainsi que le conteneur d'injection de dépendance Pimple sont mis à l'honneur avec des exemples pratiques d'usage. Ces cas pratiques combinent du code de l'ORM Propel ainsi que le composant autonome Zend\Search\Lucene du Zend Framework 2
The recent Project of the Month on SourceForge, XOOPS (http://www.xoops.org) was designed from the very beginning as an object-oriented CMS, which is even reflected in its name: eXtensible Object Oriented Portal System. Michael will present the OOP oriented architecture of XOOPS, and show how OOP makes development of XOOPS modules easy and fun, promotes reuse of code, while keeping GUI consistent across all modules.
MongoDB is an open source document database, and the leading NoSQL database. MongoDB is a document oriented database that provides high performance, high availability, and easy scalability. It is Maintained and supported by 10gen.
My first experience with MongoDB, to know what is and how can i use a NoSql (Non Relational) database, to speed up my website locality typehead, originally made with MySQL (Doctrine) queries
This webinar will walk you through building a simple location-based check-in app in MongoDB. We’ll cover the basics of MongoDB’s document model, query language, map reduce framework, and deployment architecture.
In this webinar you will discover:
- Why MongoDB is being adopted in organizations large and small
- How easy it is to start building applications with MongoDB
- Key features for manipulating and accessing data
- High availability and scale-out architecture
Come to this talk prepared to learn about the Doctrine PHP open source project. The Doctrine project has been around for over a decade and has evolved from database abstraction software that dates back to the PEAR days. The packages provided by the Doctrine project have been downloaded almost 500 million times from packagist. In this talk we will take you through how to get started with Doctrine and how to take advantage of some of the more advanced features.
Doctrine 2: Enterprise Persistence Layer for PHPJonathan Wage
Doctrine 2 is an object relational mapper (ORM) for PHP 5.3+ that sits on top of a powerful database abstraction layer (DBAL). One of its key features is the option to write database queries in a proprietary object oriented SQL dialect called Doctrine Query Language (DQL), inspired by Hibernates HQL. This provides developers with a powerful alternative to SQL that maintains flexibility without requiring unnecessary code duplication.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Building RAG with self-deployed Milvus vector database and Snowpark Container...Zilliz
This talk will give hands-on advice on building RAG applications with an open-source Milvus database deployed as a docker container. We will also introduce the integration of Milvus with Snowpark Container Services.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
20 Comprehensive Checklist of Designing and Developing a WebsitePixlogix Infotech
Dive into the world of Website Designing and Developing with Pixlogix! Looking to create a stunning online presence? Look no further! Our comprehensive checklist covers everything you need to know to craft a website that stands out. From user-friendly design to seamless functionality, we've got you covered. Don't miss out on this invaluable resource! Check out our checklist now at Pixlogix and start your journey towards a captivating online presence today.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
ZendCon2010 Doctrine MongoDB ODM
1. Jonathan H. Wage OpenSky
Doctrine MongoDB
Object Document Mapper
+
2. Who am I?
Jonathan H. Wage
PHP Developer for over 10 years
Symfony Contributor
Doctrine Contributor
Published Author
Business Owner
Nashville, TN Resident
http://www.twitter.com/jwage
http://www.facebook.com/jwage
3. I work at
What is OpenSky?
“a social commerce platform”
Based in New York and is a major open
source software advocate
http://www.shopopensky.com
7. Who is on the team?
• Roman S. Borschel
• Guilherme Blanco
• Benjamin Eberlei
• Bulat Shakirzyanov
• Jonathan H.Wage
8. Project History
- First commit April 13th 2006
- First stable version finished and Released September
1st 2008
- One of the first ORM implementations for PHP
- 1.0 is First LTS(long term support) release.
Maintained until March 1st 2010
- Integrated with many popular frameworks: Symfony,
Zend Framework, Code Igniter
9. What is MongoDB?
http://en.wikipedia.org/wiki/MongoDB
“MongoDB (from "humongous") is an open source,
scalable, high-performance, schema free, document-
oriented database written in the C++ programming
language.
The goal of MongoDB is to bridge the gap between
key-value stores - which are fast and highly scalable
- and traditional RDBMS systems - which provide rich
queries and deep functionality. It is designed for
problems that aren't easily solved by traditional
RDBMSs, for example if databases span many
servers.”
12. Using MongoDB in PHP
Download and run MongoDB Server
http://www.mongodb.org/display/DOCS/Downloads
Install Mongo PECL extension
http://www.php.net/manual/en/mongo.installation.php
$ /path/to/mongodb/bin/mongod
$ pecl install mongo
14. Selecting Databases
MongoDB intances can be selected
using the selectDB() method:
$mongo = new Mongo('mongodb://localhost');
$db = $mongo->selectDB('dbname');
15. Selecting Collections
MongoCollection instances can be
selected using the selectCollection()
method:
$mongo = new Mongo('mongodb://localhost');
$db = $mongo->selectDB('dbname');
$coll = $db->selectCollection('users');
17. Finding a Document
We can easily find the document we just
inserted using the findOne() method:
$user = $coll->findOne(array('username' => 'jwage'));
18. Updating a Document
You can find a document, change it and
save the entire document:
$user = $coll->findOne(array('username' => 'jwage'));
$user['username'] = 'jonwage';
$user['password'] = md5('newpassword');
$coll->save($user);
19. Atomic Updates
The following is faster and safer:
$coll->update(array(
'username' => 'jwage'
), array(
'$set' => array(
'username' => 'jonwage',
'password' => md5('newpassword')
)
));
20. Atomic Updates
$inc - increments field by the number value
$set - sets field to value
$unset - deletes a given field
$push - appends value to an array
$pushAll - appends multiple values to an array
$addToSet - appends multiple new values to an array
$pop - removes the last element in an array
$pull - removes all occurrences of a value from an array
$pullAll - removes all occurrences of multiple values from an array
21. Atomic Examples
Increment num_comments with $inc:
// $inc a blog posts number of comments by 1
$db->posts->update($id, array('$inc' => array('num_comments' => 1)))
22. Atomic Examples
Push new comment on to end of array:
// $push a new comment on to a blog posts comments
$db->posts->update($id, array('$push' => array(
'comments' => array('Hi how are you?')
)));
23. Atomic Examples
Set an individual field value:
// $set a lock on a blog post
$db->posts->update($id, array('$set' => array('locked' => 1)));
24. Atomic Examples
Unset a field from a document:
// $unset a lock on a blog post
$db->posts->update($id, array('$unset' => array('locked' => 1)));
25. Removing Documents
You can remove documents using the
remove() method:
$coll->remove(array('username' => 'jwage'));
27. What is it?
- Layer on top of Mongo PECL extension
- Work with objects instead of arrays
- Create rich OO PHP domain and persist
transparently using Doctrine
28. What does it do?
- Maps PHP classes to MongoDB
- Manages the state of objects
- Tracks changes and persists them
- Constructs regular PHP objects from
MongoDB data
29. How does it do it?
- Implements UnitOfWork
http://martinfowler.com/eaaCatalog/unitOfWork.html
- Tracks changes to managed objects
by maintaining a copy of its original
data
- Computes changesets and persists
them transparently
30. Easier to build than ORM
- Less work to convert objects to arrays
for persistence to MongoDB
- Less work to convert the data in the
database to objects since it is already
stored in a object-like structure
instead of flat like in a RDBMS
31. Architecture
Documents
- Lightweight persistent domain object
- Regular PHP class
- Does not extend any base Doctrine class
- Cannot be final or contain final methods
- Any two documents in a hierarchy of classes must not
have a mapped property with the same name
- Supports inheritance, polymorphic associations and
polymorphic queries.
- Both abstract and concrete classes can be documents
- Documents may extend non-document classes as well
as document classes, and non-document classes may
extend document classes
32. Architecture
- No more base class required
- Values stored in object properties
- Doctrine is transparent
namespace Documents;
class User
{
private $id;
private $name;
}
33. Architecture
The DocumentManager
- Central access point to the ODM functionality provided by
Doctrine. API is used to manage the persistence of your
objects and to query for persistent objects.
- Employes transactional write behind strategy that delays the
execution of queries in order to execute them in the most
efficient way
- Internally a DocumentManager uses a UnitOfWork to keep
track of your objects
34. Managing Documents
To manage documents with Doctrine
you need a DocumentManager:
$config = new DoctrineODMMongoDBConfiguration();
$config->setMetadataCacheImpl(new DoctrineCommonCacheArrayCache);
$driverImpl = $config->newDefaultAnnotationDriver(array(__DIR__."/Documents"));
$config->setMetadataDriverImpl($driverImpl);
$config->setProxyDir(__DIR__ . '/Proxies');
$config->setProxyNamespace('Proxies');
$dm = DoctrineODMMongoDBDocumentManager::create($mongo, $config);
35. DocumentManager
The DocumentManager is the central
place for managing the state of PHP
objects. It has methods like:
persist($document)
find()
findOne()
refresh($document)
remove($document)
detach($document)
merge($document)
flush()
36. Document Classes
A Doctrine MongoDB Document is just a regular old PHP object:
class User
{
private $id;
private $username;
private $password;
public function getId()
{
return $this->id;
}
public function getUsername()
{
return $this->username;
}
public function setUsername($username)
{
$this->username = $username;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = md5($password);
}
}
37. Mapping Information
- Annotations
- YAML
- XML
- PHP
/** @Document */
class User
{
/** @Id */
private $id;
/** @String */
private $username;
/** @String */
private $password;
// ...
}
48. Query Builder
Executing queries:
// Execute and get the first result
$user = $q->getSingleResult();
// Execute and return an array of results
$users = $q->execute();
// Execute update or remove query
$q->execute();
// Iterate over cursor
foreach ($q->iterate() as $user) {
}
50. Embedded Documents
Push a new address on to the end of
the addresses array:
$db->users->update($user['_id'], array('$push' => array(
'addresses' => array(
'address1' => 'New address'
)
51. Embedded Mapping
Map an embedded document using
@EmbedOne and @EmbedMany:
class User
{
/** @Id */
public $id;
/** @String */
public $name;
/** @EmbedMany(targetDocument="Address") */
public $addresses = array();
}
52. /** @EmbeddedDocument */
class Address
{
/** @String */
public $address;
/** @String */
public $city;
/** @String */
public $state;
/** @String */
public $zipcode;
Embedded Mapping
58. References
Reference documents from within
another document by storing an
embedded document with the following
properties:
$ref - referenced collection
$id - value of _id for the object referenced
$db - referenced database
59. References
- No JOIN syntax like in a relational DB
- References are resolved in app code
- Store one or many references
60. Reference Mapping
/** @Document */
class Organization
{
/** @Id */
private $id;
/** @String */
private $name;
/** @ReferenceMany(targetDocument="User") */
private $users = array();
public function setName($name)
{
$this->name = $name;
}
public function addUser(User $user)
{
$this->users[] = $user;
}
}
61. Reference Mapping
/** @Document */
class User
{
/** @Id */
private $id;
/** @String */
private $name;
/** @ReferenceOne(targetDocument="Organization") */
private $organization;
public function setName($name)
{
$this->name = $name;
}
public function setOrganization(Organization $organization)
{
$this->organization = $organization;
$organization->addUser($this);
}
}
62. Persisting
$organization = new Organization();
$organization->setName('Sensio Labs');
$user = new User();
$user->setName('Jonathan H. Wage');
$user->setOrganization($organization);
$dm->persist($organization);
$dm->persist($user);
$dm->flush();
63. Inserted Organization
Resulting organization has a reference
to the user:
Array
(
[_id] => 4c86acd78ead0e8759000000
[name] => Sensio Labs
[users] => Array
(
[0] => Array
(
[$ref] => User
[$id] => 4c86acd78ead0e8759010000
[$db] => doctrine_odm_sandbox
)
)
)
64. Inserted User
Resulting user has a reference to the
organization:
Array
(
[_id] => 4c86acd78ead0e8759010000
[name] => Jonathan H. Wage
[organization] => Array
(
[$ref] => Organization
[$id] => 4c86acd78ead0e8759000000
[$db] => doctrine_odm_sandbox
)
)
65. Working with References
A single reference is represented by a
proxy object:
$user = $dm->find('User', array('name' => 'Jonathan H. Wage'));
// instance of uninitialized OrganizationProxy
$organization = $user->getOrganization();
// calling getter or setter for uninitialized proxy
// queries the database and initialized the proxy document
// query invoked, organization data loaded and doc initialized
echo $organization->getName();
66. Working with References
What does a proxy look like?
class OrganizationProxy extends Organization
{
private function initialize()
{
// ...
}
public function getName()
{
$this->initialize();
return parent::getName();
}
}
67. Working with References
A many reference is represented by an
uninitialized PersistentCollection:
$organization = $dm->find('Organization', array('name' => 'Sensio Labs'));
$users = $organization->getUsers(); // uninitialized collection
// Queries database for users and initializes collection
foreach ($users as $user)
{
// ...
}
70. Creating Queries
From the DocumentManager you can
execute DQL queries using the query()
method:
$users = $dm->query('find all FROM User');
$users = $db->user->find();
74. More Examples
// Find all posts greater than or equal to a date
$posts = $dm->query('find all FROM BlogPost WHERE createdAt >= ?',
array($date));
// Find all posts sorted by created at desc
$posts = $dm->query('find all FROM BlogPost sort createdAt desc');
// Update user
$dm->query('update DocumentsUser set password = ? where username = ?',
array('newpassword', 'jwage'));
75. Events
Doctrine triggers events throughout the
lifecycle of objects it manages:
- preRemove
- postRemove
- prePersist
- postPersist
- preUpdate
- postUpdate
- preLoad
- postLoad
76. Maintaining Timestamps
/**
* @Document
* @HasLifecycleCallbacks
*/
class BlogPost
{
/** @Id */
public $id;
/** @Date */
public $createdAt;
/** @Date */
public $updatedAt;
/** @PreUpdate */
public function prePersist()
{
$this->createdAt = new DateTime();
}
/** @PreUpdate */
public function preUpdate()
{
$this->updatedAt = new DateTime();
}
}
78. Sample Scenario
Our original document looks like this:
/**
* @Document
*/
class User
{
/** @Id */
public $id;
/** @String */
public $name;
}
79. Renaming Fields
Later we want to store first and last
names in separate fields:
/**
* @Document
*/
class User
{
/** @Id */
public $id;
/** @String */
public $firstName;
/** @String */
public $lastName;
}
80. Renaming Fields
Handle documents with only a name:
/**
* @Document
* @HasLifecycleCallbacks
*/
class User
{
/** @Id */
public $id;
/** @String */
public $firstName;
/** @String */
public $lastName;
/** @PreLoad */
public function preLoad(array &$data)
{
if (isset($data['name']))
{
$e = explode(' ', $data['name']);
unset($data['name']);
$data['firstName'] = $e[0];
$data['lastName'] = $e[1];
}
}
}