SlideShare una empresa de Scribd logo
1 de 29
Object-Relational
       Mapping in PHP
PHPNW May 2009

Rob Knight - Lead Technical Architect, PRWD
http://robknight.org.uk
What is ORM?

• Manages the translation of objects into
  relational databases, and vice-versa
• Most modern programming languages,
  including PHP, have a concept of objects
• Most databases, including MySQL, Oracle
  and Postgresql are relational
Objects

• Classes define the blueprint
• Classes can inherit from each other
• Objects contain data and methods
• Object data can include other objects and
  arrays/lists
A very simple class
<?php
class Employee extends Person {
    protected $salary; // floating-point value
    protected $contractLength; // integer value


    protected $manager; // reference to another Employee object
    protected $skills; // array of 'Skill' objects


    protected $history; // array of 'History' objects


    protected $id; // unique identifier
}
Relational Databases

• Basic unit of storage is the table
• Tables can only contain simple data types
  (numbers, strings, binary data)
• No concept of arrays or lists
• Tables can be related by foreign keys
A simple table
id   name      salary    manager_id   contract_length

1    Alice   20000.00        2              12


2     Bob    150000.00     NULL           NULL


3    Clive   15000.00        5              6


4    Derek   32000.00        2            NULL


5    Edith   45000.00        2            NULL
Advantages of ORM
• Everything in PHP
• In theory, no need to understand the
  underlying data storage system
• ORM can make it easy to adopt good
  patterns and good database design
• Enables familiar OO concepts for
  manipulating data
Use of PHP concepts
<?php
$employee = new Employee(); // use of object-oriented concepts
$employee->setName(‘Joe’);
$employee->save();


// underlying database could by MySQL, SQLite, Postgres or Oracle
$peopleToFire = EmployeeTable::select(‘id’)->where(‘salary < 20000’)
   ->andWhere(‘relatedToChairman = 0’)->limit(5);




$subordinates = EmployeeTable::select(‘*’)->where(‘manager_id = ?’,
  $manager->id); // automatic variable escaping

?>
Disadvantages of ORM
• The extra layer of abstraction can be a
  performance hit
• Can be verbose
• OO isn’t always best
• Can be inflexible
• Sometimes framework-dependent
ORM can be verbose
Using Propel
$c = new Criteria();
$cton1 = $c->getNewCriterion(ArticlePeer::TITLE, '%FooBar%',
  Criteria::LIKE);
$cton1 = $c->getNewCriterion(ArticlePeer::SUMMARY, '%FooBar%',
  Criteria::LIKE);
$cton1->addOr($cton2);

$c->add($cton1);
$c->add(ArticlePeer::PUBLISHED_AT, $begin, Criteria::GREATER_THAN);
$c->addAnd(ArticlePeer::PUBLISHED_AT, $end, Criteria::LESS_THAN);

$article = ArticlePeer::doSelect($c);

SQL Query
SELECT * FROM article WHERE (title LIKE ‘%FooBar%’ OR summary LIKE
‘%FooBar’) AND published_at > {$begin} AND published_at < {$end}
There are many ORMs

• Doctrine  <http://www.doctrine-project.org>


• Propel<http://propel.phpdb.org>


• Zend_Db    <http://framework.zend.com/manual/en/zend.db.html>


• Kohana ORM       <http://docs.kohanaphp.com/libraries/orm>


• PDO <http://www.php.net/pdo>
ORM Patterns
  From ‘Patterns of Enterprise Application
  Architecture’ - Martin Fowler, 2003
• Table Data Gateway
  Zend_Db_Table, Propel ‘Peer’ classes
• Row Data Gateway
  Zend_Db_Table_Row
• Data Mapper
• Active Record
  Doctrine_Record, Propel classes
Table Data Gateway

• One class per table
• Basic functions for inserting, updating,
  deleting data from the table
• Can also handle related tables
• Data is returned in simple array/POPO
  form
An example
<?php

// Using Zend_Db_Table to fetch a record from a table

class BlogPostTable extends Zend_Db_Table_Abstract { ... }

$table = new BlogPostTable();

$select = $table->select()->where(‘author_id = ?’, $id)->order(‘created
  DESC’);

$row = $table->fetchRow($select); // row is an array, with keys for
 column names

echo $row->title; // prints the title of the blog post

?>
Row Data Gateway



• Class for manipulating a single row
• Separates finding/searching from
  manipulation
• Database access logic only
An example
<?php

// create row using table object
$table = new BlogPostTable();
$newRow = $table->createRow();

// set values
$newRow->title = ‘New Blog Post’;
$newRow->body = ‘Lorem ipsum....’;

// save the row to the table
$newRow->save();

?>
Active Record


• Similar to Row Data Gateway
• Classes inherit from a ‘Record’ class
• Classes may also implement ‘behaviours’
• Some mixing of data storage code and
  domain logic
An example
<?php

class User extends Doctrine_Record {
   public function setTableDefinition() {
     $this->hasColumn('username', 'string', 255);
     $this->hasColumn('password', 'string', 255);
   }

    public function authenticate($username, $password) {
      return ($this->username == $username) && ($this->password == $password);
    }
}

$table = Doctrine::getTable(‘User’);

$user = $table->find($id);

if ($user->authenticate($username, $password)) {
    print “Authenticated as user id {$id}”;
}
Data Mapper


• Takes your object model and saves it to
  database
• Mapper is external to your classes
• Good separation of concerns, keeps the
  OO away from the data
• Hard to implement as a ‘drop-in’ system
Extras

• Schema management
• Auto-creation of forms, admin areas
• Database creation and migration
• Plugins and behaviours
Schemas
User:
 tableName: users
 columns:
  id:
    type: integer(4)
    primary: true
    autoincrement: true
    unsigned: true
  forename:
    type: string(50)
  surname:
    type: string(50)
  email:
    type: string(50)
  password:
    type: string(32)
 actAs:
  Timestampable:
    created:
      name: created
      type: integer
      options:
      unsigned: true
Plugins
• Logging
• Profiling
• Behaviours - timestampable, sluggable and
  more
• Events
• Inheritance
• Caching
Performance Issues
• Joins
  Complex relationships between objects can
  lead to inefficient joins between tables
• ‘Hydration’
  Transforming database rows into full PHP
  objects can be expensive
• Many classes, many files
  Loading many auto-generated classes can
  cause performance issues
Alternatives

• Object databases
• Document databases
• Key-value stores
• Hybrids
Object and Document
     Databases
• Persevere
  Stores JavaScript/JSON objects
• CouchDB
  Stores documents in JSON format
• Abdera
  Stores documents using the Atom
  Publishing Protocol
Key-value stores

• SimpleDB
• BigTable
• Mnesia
JSON: a better fit?
employees: [
  {
    name: “Alice”,
    salary: 35000.00,
    skills: [
      “C++”, “PHP”, “SQL”
    ]
  },
  {
    name: “Bob”,
    salary: 24000.00,
    skills: [
      “Java”, “C#”
    ]
  }
]




Might JSON object storage be better for PHP?
Conclusions

• Choose your ORM library carefully
• Experiment
• Don’t over-complicate
• Maybe ORM is the wrong choice anyway?
• Alternatives are starting to become viable
Thanks for listening

Any questions?



Slides available at http://robknight.org.uk/presentations

Más contenido relacionado

La actualidad más candente

Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Christian Schneider
 
1 03 - CSS Introduction
1 03 - CSS Introduction1 03 - CSS Introduction
1 03 - CSS Introductionapnwebdev
 
When To Use Ruby On Rails
When To Use Ruby On RailsWhen To Use Ruby On Rails
When To Use Ruby On Railsdosire
 
Media queries A to Z
Media queries A to ZMedia queries A to Z
Media queries A to ZShameem Reza
 
Introduction to back-end
Introduction to back-endIntroduction to back-end
Introduction to back-endMosaab Ehab
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The BasicsJeff Fox
 
Writing php extensions in golang
Writing php extensions in golangWriting php extensions in golang
Writing php extensions in golangdo_aki
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Express JS Rest API Tutorial
Express JS Rest API TutorialExpress JS Rest API Tutorial
Express JS Rest API TutorialSimplilearn
 
JavaScript - Chapter 1 - Problem Solving
 JavaScript - Chapter 1 - Problem Solving JavaScript - Chapter 1 - Problem Solving
JavaScript - Chapter 1 - Problem SolvingWebStackAcademy
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6Rob Eisenberg
 

La actualidad más candente (20)

Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
 
Expressjs
ExpressjsExpressjs
Expressjs
 
1 03 - CSS Introduction
1 03 - CSS Introduction1 03 - CSS Introduction
1 03 - CSS Introduction
 
When To Use Ruby On Rails
When To Use Ruby On RailsWhen To Use Ruby On Rails
When To Use Ruby On Rails
 
Media queries A to Z
Media queries A to ZMedia queries A to Z
Media queries A to Z
 
Introduction to back-end
Introduction to back-endIntroduction to back-end
Introduction to back-end
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
CSS Grid
CSS GridCSS Grid
CSS Grid
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Writing php extensions in golang
Writing php extensions in golangWriting php extensions in golang
Writing php extensions in golang
 
SPARQL Tutorial
SPARQL TutorialSPARQL Tutorial
SPARQL Tutorial
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Express JS Rest API Tutorial
Express JS Rest API TutorialExpress JS Rest API Tutorial
Express JS Rest API Tutorial
 
JavaScript - Chapter 1 - Problem Solving
 JavaScript - Chapter 1 - Problem Solving JavaScript - Chapter 1 - Problem Solving
JavaScript - Chapter 1 - Problem Solving
 
PHP Presentation
PHP PresentationPHP Presentation
PHP Presentation
 
Json
JsonJson
Json
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 

Destacado

What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3Jeremy Coates
 
JDXA, The KISS ORM for Android
JDXA, The KISS ORM for AndroidJDXA, The KISS ORM for Android
JDXA, The KISS ORM for AndroidDamodar Periwal
 
좌충우돌 ORM 개발기 2012 DAUM DEVON
좌충우돌 ORM 개발기 2012 DAUM DEVON좌충우돌 ORM 개발기 2012 DAUM DEVON
좌충우돌 ORM 개발기 2012 DAUM DEVONYounghan Kim
 
좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012Daum DNA
 
About Orm.fm
About Orm.fmAbout Orm.fm
About Orm.fmOrm Moon
 
Ling to SQL and Entity Framework performance analysis
Ling to SQL and Entity Framework performance analysisLing to SQL and Entity Framework performance analysis
Ling to SQL and Entity Framework performance analysisAlexander Konduforov
 
ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정Javajigi Jaesung
 
QnA blog using Django - ORM, 회원가입, 로그인/로그아웃
QnA blog using Django - ORM, 회원가입, 로그인/로그아웃QnA blog using Django - ORM, 회원가입, 로그인/로그아웃
QnA blog using Django - ORM, 회원가입, 로그인/로그아웃Kwangyoun Jung
 
Object Relational Mapping In Real World Applications
Object Relational Mapping In Real World ApplicationsObject Relational Mapping In Real World Applications
Object Relational Mapping In Real World ApplicationsPhilWinstanley
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational MappingRanjan Kumar
 
Object-Relational Mapping and Dependency Injection
Object-Relational Mapping and Dependency InjectionObject-Relational Mapping and Dependency Injection
Object-Relational Mapping and Dependency InjectionShane Church
 
Automated functional size measurement for three tier object relational mappin...
Automated functional size measurement for three tier object relational mappin...Automated functional size measurement for three tier object relational mappin...
Automated functional size measurement for three tier object relational mappin...IWSM Mensura
 
기술적 변화를 이끌어가기
기술적 변화를 이끌어가기기술적 변화를 이끌어가기
기술적 변화를 이끌어가기Jaewoo Ahn
 
SK플래닛_README_마이크로서비스 아키텍처로 개발하기
SK플래닛_README_마이크로서비스 아키텍처로 개발하기SK플래닛_README_마이크로서비스 아키텍처로 개발하기
SK플래닛_README_마이크로서비스 아키텍처로 개발하기Lee Ji Eun
 

Destacado (16)

What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3
 
L18 Object Relational Mapping
L18 Object Relational MappingL18 Object Relational Mapping
L18 Object Relational Mapping
 
JDXA, The KISS ORM for Android
JDXA, The KISS ORM for AndroidJDXA, The KISS ORM for Android
JDXA, The KISS ORM for Android
 
좌충우돌 ORM 개발기 2012 DAUM DEVON
좌충우돌 ORM 개발기 2012 DAUM DEVON좌충우돌 ORM 개발기 2012 DAUM DEVON
좌충우돌 ORM 개발기 2012 DAUM DEVON
 
좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012
 
L16 Object Relational Mapping and NoSQL
L16 Object Relational Mapping and NoSQLL16 Object Relational Mapping and NoSQL
L16 Object Relational Mapping and NoSQL
 
About Orm.fm
About Orm.fmAbout Orm.fm
About Orm.fm
 
Ling to SQL and Entity Framework performance analysis
Ling to SQL and Entity Framework performance analysisLing to SQL and Entity Framework performance analysis
Ling to SQL and Entity Framework performance analysis
 
ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정
 
QnA blog using Django - ORM, 회원가입, 로그인/로그아웃
QnA blog using Django - ORM, 회원가입, 로그인/로그아웃QnA blog using Django - ORM, 회원가입, 로그인/로그아웃
QnA blog using Django - ORM, 회원가입, 로그인/로그아웃
 
Object Relational Mapping In Real World Applications
Object Relational Mapping In Real World ApplicationsObject Relational Mapping In Real World Applications
Object Relational Mapping In Real World Applications
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational Mapping
 
Object-Relational Mapping and Dependency Injection
Object-Relational Mapping and Dependency InjectionObject-Relational Mapping and Dependency Injection
Object-Relational Mapping and Dependency Injection
 
Automated functional size measurement for three tier object relational mappin...
Automated functional size measurement for three tier object relational mappin...Automated functional size measurement for three tier object relational mappin...
Automated functional size measurement for three tier object relational mappin...
 
기술적 변화를 이끌어가기
기술적 변화를 이끌어가기기술적 변화를 이끌어가기
기술적 변화를 이끌어가기
 
SK플래닛_README_마이크로서비스 아키텍처로 개발하기
SK플래닛_README_마이크로서비스 아키텍처로 개발하기SK플래닛_README_마이크로서비스 아키텍처로 개발하기
SK플래닛_README_마이크로서비스 아키텍처로 개발하기
 

Similar a Object Relational Mapping in PHP

Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Data Con LA
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redisjimbojsb
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
Synapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindiaComplaints
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardJAX London
 
Framework Presentation
Framework PresentationFramework Presentation
Framework Presentationrmalik2
 
Jooctrine - Doctrine ORM in Joomla!
Jooctrine - Doctrine ORM in Joomla!Jooctrine - Doctrine ORM in Joomla!
Jooctrine - Doctrine ORM in Joomla!Herman Peeren
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in PerlLaurent Dami
 
Slow Database in your PHP stack? Don't blame the DBA!
Slow Database in your PHP stack? Don't blame the DBA!Slow Database in your PHP stack? Don't blame the DBA!
Slow Database in your PHP stack? Don't blame the DBA!Harald Zeitlhofer
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpMichael Girouard
 

Similar a Object Relational Mapping in PHP (20)

Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
 
Api Design
Api DesignApi Design
Api Design
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
 
Php summary
Php summaryPhp summary
Php summary
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
Synapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephp
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Pecl Picks
Pecl PicksPecl Picks
Pecl Picks
 
Os Furlong
Os FurlongOs Furlong
Os Furlong
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
 
Framework Presentation
Framework PresentationFramework Presentation
Framework Presentation
 
Jooctrine - Doctrine ORM in Joomla!
Jooctrine - Doctrine ORM in Joomla!Jooctrine - Doctrine ORM in Joomla!
Jooctrine - Doctrine ORM in Joomla!
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
 
Slow Database in your PHP stack? Don't blame the DBA!
Slow Database in your PHP stack? Don't blame the DBA!Slow Database in your PHP stack? Don't blame the DBA!
Slow Database in your PHP stack? Don't blame the DBA!
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
DataMapper
DataMapperDataMapper
DataMapper
 
Fatc
FatcFatc
Fatc
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 

Último

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Último (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Object Relational Mapping in PHP

  • 1. Object-Relational Mapping in PHP PHPNW May 2009 Rob Knight - Lead Technical Architect, PRWD http://robknight.org.uk
  • 2. What is ORM? • Manages the translation of objects into relational databases, and vice-versa • Most modern programming languages, including PHP, have a concept of objects • Most databases, including MySQL, Oracle and Postgresql are relational
  • 3. Objects • Classes define the blueprint • Classes can inherit from each other • Objects contain data and methods • Object data can include other objects and arrays/lists
  • 4. A very simple class <?php class Employee extends Person { protected $salary; // floating-point value protected $contractLength; // integer value protected $manager; // reference to another Employee object protected $skills; // array of 'Skill' objects protected $history; // array of 'History' objects protected $id; // unique identifier }
  • 5. Relational Databases • Basic unit of storage is the table • Tables can only contain simple data types (numbers, strings, binary data) • No concept of arrays or lists • Tables can be related by foreign keys
  • 6. A simple table id name salary manager_id contract_length 1 Alice 20000.00 2 12 2 Bob 150000.00 NULL NULL 3 Clive 15000.00 5 6 4 Derek 32000.00 2 NULL 5 Edith 45000.00 2 NULL
  • 7. Advantages of ORM • Everything in PHP • In theory, no need to understand the underlying data storage system • ORM can make it easy to adopt good patterns and good database design • Enables familiar OO concepts for manipulating data
  • 8. Use of PHP concepts <?php $employee = new Employee(); // use of object-oriented concepts $employee->setName(‘Joe’); $employee->save(); // underlying database could by MySQL, SQLite, Postgres or Oracle $peopleToFire = EmployeeTable::select(‘id’)->where(‘salary < 20000’) ->andWhere(‘relatedToChairman = 0’)->limit(5); $subordinates = EmployeeTable::select(‘*’)->where(‘manager_id = ?’, $manager->id); // automatic variable escaping ?>
  • 9. Disadvantages of ORM • The extra layer of abstraction can be a performance hit • Can be verbose • OO isn’t always best • Can be inflexible • Sometimes framework-dependent
  • 10. ORM can be verbose Using Propel $c = new Criteria(); $cton1 = $c->getNewCriterion(ArticlePeer::TITLE, '%FooBar%', Criteria::LIKE); $cton1 = $c->getNewCriterion(ArticlePeer::SUMMARY, '%FooBar%', Criteria::LIKE); $cton1->addOr($cton2); $c->add($cton1); $c->add(ArticlePeer::PUBLISHED_AT, $begin, Criteria::GREATER_THAN); $c->addAnd(ArticlePeer::PUBLISHED_AT, $end, Criteria::LESS_THAN); $article = ArticlePeer::doSelect($c); SQL Query SELECT * FROM article WHERE (title LIKE ‘%FooBar%’ OR summary LIKE ‘%FooBar’) AND published_at > {$begin} AND published_at < {$end}
  • 11. There are many ORMs • Doctrine <http://www.doctrine-project.org> • Propel<http://propel.phpdb.org> • Zend_Db <http://framework.zend.com/manual/en/zend.db.html> • Kohana ORM <http://docs.kohanaphp.com/libraries/orm> • PDO <http://www.php.net/pdo>
  • 12. ORM Patterns From ‘Patterns of Enterprise Application Architecture’ - Martin Fowler, 2003 • Table Data Gateway Zend_Db_Table, Propel ‘Peer’ classes • Row Data Gateway Zend_Db_Table_Row • Data Mapper • Active Record Doctrine_Record, Propel classes
  • 13. Table Data Gateway • One class per table • Basic functions for inserting, updating, deleting data from the table • Can also handle related tables • Data is returned in simple array/POPO form
  • 14. An example <?php // Using Zend_Db_Table to fetch a record from a table class BlogPostTable extends Zend_Db_Table_Abstract { ... } $table = new BlogPostTable(); $select = $table->select()->where(‘author_id = ?’, $id)->order(‘created DESC’); $row = $table->fetchRow($select); // row is an array, with keys for column names echo $row->title; // prints the title of the blog post ?>
  • 15. Row Data Gateway • Class for manipulating a single row • Separates finding/searching from manipulation • Database access logic only
  • 16. An example <?php // create row using table object $table = new BlogPostTable(); $newRow = $table->createRow(); // set values $newRow->title = ‘New Blog Post’; $newRow->body = ‘Lorem ipsum....’; // save the row to the table $newRow->save(); ?>
  • 17. Active Record • Similar to Row Data Gateway • Classes inherit from a ‘Record’ class • Classes may also implement ‘behaviours’ • Some mixing of data storage code and domain logic
  • 18. An example <?php class User extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('username', 'string', 255); $this->hasColumn('password', 'string', 255); } public function authenticate($username, $password) { return ($this->username == $username) && ($this->password == $password); } } $table = Doctrine::getTable(‘User’); $user = $table->find($id); if ($user->authenticate($username, $password)) { print “Authenticated as user id {$id}”; }
  • 19. Data Mapper • Takes your object model and saves it to database • Mapper is external to your classes • Good separation of concerns, keeps the OO away from the data • Hard to implement as a ‘drop-in’ system
  • 20. Extras • Schema management • Auto-creation of forms, admin areas • Database creation and migration • Plugins and behaviours
  • 21. Schemas User: tableName: users columns: id: type: integer(4) primary: true autoincrement: true unsigned: true forename: type: string(50) surname: type: string(50) email: type: string(50) password: type: string(32) actAs: Timestampable: created: name: created type: integer options: unsigned: true
  • 22. Plugins • Logging • Profiling • Behaviours - timestampable, sluggable and more • Events • Inheritance • Caching
  • 23. Performance Issues • Joins Complex relationships between objects can lead to inefficient joins between tables • ‘Hydration’ Transforming database rows into full PHP objects can be expensive • Many classes, many files Loading many auto-generated classes can cause performance issues
  • 24. Alternatives • Object databases • Document databases • Key-value stores • Hybrids
  • 25. Object and Document Databases • Persevere Stores JavaScript/JSON objects • CouchDB Stores documents in JSON format • Abdera Stores documents using the Atom Publishing Protocol
  • 26. Key-value stores • SimpleDB • BigTable • Mnesia
  • 27. JSON: a better fit? employees: [ { name: “Alice”, salary: 35000.00, skills: [ “C++”, “PHP”, “SQL” ] }, { name: “Bob”, salary: 24000.00, skills: [ “Java”, “C#” ] } ] Might JSON object storage be better for PHP?
  • 28. Conclusions • Choose your ORM library carefully • Experiment • Don’t over-complicate • Maybe ORM is the wrong choice anyway? • Alternatives are starting to become viable
  • 29. Thanks for listening Any questions? Slides available at http://robknight.org.uk/presentations

Notas del editor