SlideShare a Scribd company logo
The History of PHPersistence
The History of PHPersistence
       Hugo Hamon - @hhamon
       OSIDays November 2011
PHP/FI

Where Everything Begins…
1995

PHP/FI
1995

Files handling
$fp = fopen("/counter.txt","w+");	
	
$counter = fgets($fp,1024);	
$counter++;	
	
fputs($fp, $counter);	
fclose($fp);	
  
1995

Databases support
$db = mysql_connect("localhost", "root", "secret");

$name = "bob";

$result = mysql(
    $db,
    "select * from table where firstname='$name'"
);

$num = mysql_numrows($result);

echo "$num records found!<p>";
$i=0;
while ($i<$num);

    echo mysql_result($result,$i,"lcase(fullname)");
    echo "n";

    echo mysql_result($result,$i,"address");
    echo "n";

    $i++;

endwhile;
PHP 3/4

Code Reusability
User Functions
function db_connect($database, $host, $user, $pwd);

function db_fetch_single($dbh, $query);

function db_fetch_all($dbh, $query);

function db_insert($dbh, $table, $values);

function db_update($dbh, $table, $values, $pk);

function db_delete($dbh, $table, $pk);

function db_list_fields($dbh, $table);

function db_drop_table($dbh, $table);
function db_connect($database, $host, $user, $pwd)
{
    $dbh = mysql_connect($host, $user, $pwd);

    if (!$dbh) {
        die('Server unavailable: '. mysql_error());
    }

    if (!mysql_select_db($database, $dbh)) {
        die("'$database' unavailable: ". mysql_error());
    }

    return $dbh;
}
/**
  * Fetches a single record from a database
  *
  * @param resource $dbh The database handler
  * @param string $query A SQL query
  * @return array A single record as an array
  */
function db_fetch_single($dbh, $query)
{
     return current(db_fetch_all($dbh, $query));
}
function db_fetch_all($dbh, $query)
{
    $result = mysql_query($query, $dbh);
    if (!$result) {
        die('Invalid query: '. mysql_error());
    }

    $records = array();
    while ($record = mysql_fetch_assoc($result)) {
        $records[] = $record;
    }

    return $records;
}
function db_insert($dbh, $table, array $values)
{
    $data = array();
    foreach ($values as $value) {
        $data[] = mysql_real_escape_string($value, $dbh);
    }

    $sql = sprintf("INSERT INTO `$table` (`%s`) VALUES ('%s')",
        implode('`, `', array_keys($values)),
        implode("', '", $data)
    );

    $result = mysql_query($query, $dbh);
    if (!$result) {
        die('Invalid data to insert: '. mysql_error());
    }

    return mysql_insert_id($dbh);
}
include 'lib/database.inc.php';

$dbh = db_connect('osidays');
$query = 'SELECT id, name FROM author';

$authors = db_fetch_all($dbh, $query);
$author = db_fetch_single(
    $dbh,
    'SELECT id, name FROM author WHERE id = 3'
);

$id = db_insert($dbh, 'author', array(
    'name' => 'Jules Verne'
));
PHP 4

OOP & Reusability
class Database
{
    function Database($database, host, $user, $pwd);

    function   disconnect();
    function   connect();
    function   free();
    function   getErrorMessage();
    function   getErrorCode();
    function   getLastInsertId();
    function   insert($table, array $values);
    function   fetchAll($query);
    function   fetchSingle($query);
    function   query($query);
    function   quote($string);
    function   hasError();
    function   _collectError();
    function   _init();
}
require 'lib/Database.php';

$db= &new Database('demo', 'localhost', 'root');

$q = 'SELECT id, name FROM author';

foreach ($db->fetchAll($q) as $author) {
    // ...
}

$db->free();
$db->disconnect();
require 'lib/Database.php';

$db= &new Database('demo', 'localhost', 'root');

$q = 'SELECT id, name FROM author WHERE id = 1';

$author = $db->fetchSingle($q);

$db->free();

$db->disconnect();
require 'lib/Database.php';

$db= &new Database('demo', 'localhost', 'root');

$res = $db->insert('author', array(
    'name' => 'Jules Vernes'
));

if ($result) {
    $id = $db->getLastInsertId();
}

$db->disconnect();
PHP 4

Professional APIs
DBAL
• PEAR::DB   • MDB
• ADOdb      • MDB2
• Metabase • Creole
§  Multiple databases support
§  Uni ed APIs
§  Prepared statements supports
§  Query caching
§  Security against SQL Injections
PEAR MDB2
$dsn = array(
    'phptype'    =>   'mysql',
    'username'   =>   'root',
    'password'   =>   '',
    'hostspec'   =>   'localhost',
    'database'   =>   'demo',
);

$db = & MDB2::connect($dsn);
$db->setFetchMode(MDB2_FETCHMODE_ASSOC);

$rs = $db->queryAll('SELECT id, name FROM author');

$db->disconnect();
ADOdb
include('adodb.inc.php');

$db = NewADOConnection('mysql');
$db->Connect('localhost', 'root', 'password', 'demo');

$result = $db->Execute('SELECT id, name FROM author');

if ($result) {
    while (!$result->EOF) {
        echo 'ID: ', $result->fields[0] ,"n";
        echo 'Name:', $result->fields[1] ,"n";
        $result->MoveNext();
    }
}
2004

PHP 5
2005

PHP Data Object
•  PECL extension as of PHP 5.0.0
•  Core extension since PHP 5.1.0 (11/2005)
•  12 official drivers as of today
•  Extensible Object Oriented API
•  Prepared statements & transaction support
•  Stored procedures support
The History of PHPersistence
« PDO provides a data-access abstraction
layer, which means that, regardless of
which database you're using, you use the
same functions to issue queries and fetch
data. »
« PDO does not provide a
database abstraction as it
doesn't rewrite SQL or emulate
missing features »
Transactions
         /
Prepared Statements
try {
  $pdo->beginTransaction();

 $query = 'INSERT INTO author (name) VALUES (?)';

 $stmt = $pdo->prepare($query);
 $stmt->bindValue(1, 'Jules Verne');
 $stmt->execute();

  $id = $pdo->lastInsertId();
  $pdo->commit();
} catch (PDOException $e) {
  $pdo->rollback();
}
Stored Procedures
DELIMITER |
CREATE PROCEDURE coming_events (IN start DATE, OUT events INT)
BEGIN
  SELECT COUNT(*) INTO events FROM events WHERE start_at >=
start;
END
|


$query = "CALL coming_events('2011-03-01', @events);";

$pdo->query($query);

$stmt = $pdo->query("SELECT @events;");

echo $stmt->fetchColumn() ,' events to come.';
PHP 5

Zend_Db
Table Data Gateway
class AuthorGateway
    extends Zend_Db_Table_Abstract
{

    protected $_name = 'authors';
    protected $_primary = 'author_id';

}
$data = array(
    'first_name' => 'Jules',
    'last_name' => 'Vernes',
);

$table = new AuthorGateway();
$table->insert($data);
Row Data Gateway
$table = new AuthorGateway();

// New empty row
$row = $table->createRow();

// Insert a new row
$row->firstName = 'Jules';
$row->lastName = 'Verne';
$row->save();
Active Query
$isbn = '1234567890';

$rows = $db->select()
    ->from(array('b' => 'books'))
    ->where('b.isbn = ?', $isbn)
    ->order(array('b.title ASC'))
    ->query()
    ->fetchAll()
;
PHP 5

Object Relational Mapping
•  Use objects instead of raw SQL queries

•  Database abstraction layer (not always)

•  Relationships support

•  Behaviors support (i18n, timestampable…)

•  Querying API

•  Error logging
2005

Propel ORM
$author = new Author();
$author->setFirstName("Leo");
$author->setLastName("Tolstoy");

$book = new Book();
$book->setTitle("War & Peace");
$book->setIsbn("0140444173");
$book->setAuthor($author);
$book->save();
$query = BookQuery::create()
  ->joinWith('Book.Author')
  ->joinWith('Book.Publisher')
  ->where('Author.firstName = ?', 'Leo')
  ->where('Author.lastName = ?', 'Tolstoï')
  ->orderByTitle()
  ->filterByPublishYear(2009)
  ->find()
;
2009

Doctrine 1.x
$books = Doctrine_Query::create()
    ->select('b.*, a.*, p.*')
    ->from('Book b')
    ->leftJoin('b.Author a')
    ->leftJoin('b.Publisher p')
    ->where('a.firstName = ?', 'Karl')
    ->andWhere('a.lastName = ?', 'Marx')
    ->orderBy('b.title ASC')
    ->execute()
;
2009	
  
   	
  
PHP	
  5.3	
  
ORM Frameworks
Doctrine2
•  Database Abstraction Layer

•  Object Relational Mapping

•  Schema management

•  Migrations support

•  XML & NoSQL databases support
/** @Entity() */
class Author
{
  /**
   * @Id()
   * @GeneratedValue()
   * @Column(type="integer")
   */
  private $id;

    /** @Column(type="string", length="30") */
    private $name;

    /** @ReferenceMany(targetDocument="BlogPost") */
    private $posts = array();
}
$post = new BlogPost();
$post->setTitle('My First Blog Post');
$post->setBody('Some content...');

$author = new Author();
$author->setName('Hugo Hamon');
$author->addPost($post);

$em->persist($user);
$em->persist($post);
$dm->flush();
Toward NoSQL…
«	
  Not	
  Only	
  SQL	
  »	
  
Key   abcdef	
     Hugo	
  Hamon	
     Value
FirstName:	
  Hugo	
     Column 1

Key   abcdef	
     LastName:	
  Hamon	
      Column 2

                     Role:	
  Speaker	
      Column 3
Document
Key

  abcdef	
     Name:	
  Hugo	
  Hamon	
  


                                            0:	
  PHP	
  


               Skills	
                     1:	
  HTML	
  


                                            2:	
  CSS	
  


               Role:	
  Speaker	
  
2009

MongoDB Driver
•  Cross-platform support

•  Schemaless language

•  BSON type support

•  Binary le storage support (GridFS)

•  Master – slave replication support

•  Sharding (horizontal scaling)
$mongo = new Mongo();

$col = $mongo->selectDb('osidays')->books;

$books = array(
    array('title' => 'Da Vinci Code'),
    array('title' => 'The Lost Symbol'),
    array('title' => 'Digital Fortress'),
);

foreach ($books as $book) {
    $collection->insert($book);
}
What’s next…
… for today and tomorrow?
2011

PHP 5.3 ODM Frameworks
The History of PHPersistence
•  ORM Layers for Mongodb
•  Dealing with objects instead of arrays
•  Relationships support
•  Query abstraction
•  GridFS support
•  Query logging & caching
$post = new BlogPost();
$post->setTitle('My First Blog Post');
$post->setBody('Some content...');

$author = new Author();
$author->setName('Hugo Hamon');
$author->setEmail('hugo@example.com');

$dm->persist($user);
$user->addPost($post);

$dm->flush();
QuesAons?	
  




 92-98, boulevard Victor Hugo
 92 115 Clichy Cedex
 trainings@sensio.com (+33 (0)1 40 99 82 11)

 sensiolabs.com - symfony.com – trainings.sensiolabs.com

More Related Content

What's hot

Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
Bill Chang
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
Leonardo Proietti
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
Nate Abele
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Nate Abele
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
Fabien Potencier
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Kacper Gunia
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm Old
Ross Tuck
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
Guilherme Blanco
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Masahiro Nagano
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
Konstantin Kudryashov
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
Kacper Gunia
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
Guilherme Blanco
 
Object Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPObject Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHP
Chad Gray
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
Rafael Dohms
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
Mark Baker
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
Sam Hennessy
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
Konstantin Kudryashov
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
Kris Wallsmith
 

What's hot (20)

Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm Old
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
Object Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPObject Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHP
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 

Viewers also liked

Monitor the quality of your Symfony projects
Monitor the quality of your Symfony projectsMonitor the quality of your Symfony projects
Monitor the quality of your Symfony projects
Hugo Hamon
 
Api 101
Api 101Api 101
Symfony2 - Un Framework PHP 5 Performant
Symfony2 - Un Framework PHP 5 PerformantSymfony2 - Un Framework PHP 5 Performant
Symfony2 - Un Framework PHP 5 Performant
Hugo Hamon
 
Quantifying fitness
Quantifying fitnessQuantifying fitness
Quantifying fitness
Kirsten Hunter
 
Liberating your data
Liberating your dataLiberating your data
Liberating your data
Kirsten Hunter
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
Hugo Hamon
 
This stuff is cool, but...HOW CAN I GET MY COMPANY TO DO IT?
This stuff is cool, but...HOW CAN I GET MY COMPANY TO DO IT?This stuff is cool, but...HOW CAN I GET MY COMPANY TO DO IT?
This stuff is cool, but...HOW CAN I GET MY COMPANY TO DO IT?
Mark Heckler
 
Symfony2 en pièces détachées
Symfony2 en pièces détachéesSymfony2 en pièces détachées
Symfony2 en pièces détachées
Hugo Hamon
 
Développeurs, cachez-moi ça ! (Paris Web 2011)
Développeurs, cachez-moi ça ! (Paris Web 2011)Développeurs, cachez-moi ça ! (Paris Web 2011)
Développeurs, cachez-moi ça ! (Paris Web 2011)
Hugo Hamon
 
Liberating your data
Liberating your dataLiberating your data
Liberating your data
Kirsten Hunter
 
API First
API FirstAPI First
API First
Kirsten Hunter
 
Facebook appsincloud
Facebook appsincloudFacebook appsincloud
Facebook appsincloud
Kirsten Hunter
 
Designing for developers
Designing for developersDesigning for developers
Designing for developers
Kirsten Hunter
 
Prototyping in the cloud
Prototyping in the cloudPrototyping in the cloud
Prototyping in the cloud
Kirsten Hunter
 
API 101 Workshop from APIStrat Conference
API 101 Workshop from APIStrat ConferenceAPI 101 Workshop from APIStrat Conference
API 101 Workshop from APIStrat Conference
Kirsten Hunter
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console component
Hugo Hamon
 
Polyglot copy
Polyglot copyPolyglot copy
Polyglot copy
Kirsten Hunter
 
Git store
Git storeGit store
Git store
Kirsten Hunter
 
Api intensive - What they Are
Api intensive - What they AreApi intensive - What they Are
Api intensive - What they Are
Kirsten Hunter
 
Quantifying your-fitness
Quantifying your-fitnessQuantifying your-fitness
Quantifying your-fitness
Kirsten Hunter
 

Viewers also liked (20)

Monitor the quality of your Symfony projects
Monitor the quality of your Symfony projectsMonitor the quality of your Symfony projects
Monitor the quality of your Symfony projects
 
Api 101
Api 101Api 101
Api 101
 
Symfony2 - Un Framework PHP 5 Performant
Symfony2 - Un Framework PHP 5 PerformantSymfony2 - Un Framework PHP 5 Performant
Symfony2 - Un Framework PHP 5 Performant
 
Quantifying fitness
Quantifying fitnessQuantifying fitness
Quantifying fitness
 
Liberating your data
Liberating your dataLiberating your data
Liberating your data
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
 
This stuff is cool, but...HOW CAN I GET MY COMPANY TO DO IT?
This stuff is cool, but...HOW CAN I GET MY COMPANY TO DO IT?This stuff is cool, but...HOW CAN I GET MY COMPANY TO DO IT?
This stuff is cool, but...HOW CAN I GET MY COMPANY TO DO IT?
 
Symfony2 en pièces détachées
Symfony2 en pièces détachéesSymfony2 en pièces détachées
Symfony2 en pièces détachées
 
Développeurs, cachez-moi ça ! (Paris Web 2011)
Développeurs, cachez-moi ça ! (Paris Web 2011)Développeurs, cachez-moi ça ! (Paris Web 2011)
Développeurs, cachez-moi ça ! (Paris Web 2011)
 
Liberating your data
Liberating your dataLiberating your data
Liberating your data
 
API First
API FirstAPI First
API First
 
Facebook appsincloud
Facebook appsincloudFacebook appsincloud
Facebook appsincloud
 
Designing for developers
Designing for developersDesigning for developers
Designing for developers
 
Prototyping in the cloud
Prototyping in the cloudPrototyping in the cloud
Prototyping in the cloud
 
API 101 Workshop from APIStrat Conference
API 101 Workshop from APIStrat ConferenceAPI 101 Workshop from APIStrat Conference
API 101 Workshop from APIStrat Conference
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console component
 
Polyglot copy
Polyglot copyPolyglot copy
Polyglot copy
 
Git store
Git storeGit store
Git store
 
Api intensive - What they Are
Api intensive - What they AreApi intensive - What they Are
Api intensive - What they Are
 
Quantifying your-fitness
Quantifying your-fitnessQuantifying your-fitness
Quantifying your-fitness
 

Similar to The History of PHPersistence

Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Rifat Nabi
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
chuvainc
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the Good
Jeremy Kendall
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
Jeremy Kendall
 
Presentation1
Presentation1Presentation1
Presentation1
Rahadyan Gusti
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
Nicolas Leroy
 
DBI
DBIDBI
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
Rafael Dohms
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
Night Sailer
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
 
Database api
Database apiDatabase api
Database api
InternetDevels
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
Viswanath Polaki
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
waraiotoko
 
与 PHP 和 Perl 使用 MySQL 数据库
与 PHP 和 Perl 使用 MySQL 数据库与 PHP 和 Perl 使用 MySQL 数据库
与 PHP 和 Perl 使用 MySQL 数据库
YUCHENG HU
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
Taras Kalapun
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
iKlaus
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
Ismail Mukiibi
 
php2.pptx
php2.pptxphp2.pptx
php2.pptx
ElieNGOMSEU
 
wget.pl
wget.plwget.pl
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
Jeff Carouth
 

Similar to The History of PHPersistence (20)

Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the Good
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
 
Presentation1
Presentation1Presentation1
Presentation1
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
 
DBI
DBIDBI
DBI
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Database api
Database apiDatabase api
Database api
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
 
与 PHP 和 Perl 使用 MySQL 数据库
与 PHP 和 Perl 使用 MySQL 数据库与 PHP 和 Perl 使用 MySQL 数据库
与 PHP 和 Perl 使用 MySQL 数据库
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
php2.pptx
php2.pptxphp2.pptx
php2.pptx
 
wget.pl
wget.plwget.pl
wget.pl
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 

More from Hugo Hamon

Intégration Continue PHP avec Jenkins CI
Intégration Continue PHP avec Jenkins CIIntégration Continue PHP avec Jenkins CI
Intégration Continue PHP avec Jenkins CI
Hugo Hamon
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
Hugo Hamon
 
Intégration continue des projets PHP avec Jenkins
Intégration continue des projets PHP avec JenkinsIntégration continue des projets PHP avec Jenkins
Intégration continue des projets PHP avec Jenkins
Hugo Hamon
 
Mieux Développer en PHP avec Symfony
Mieux Développer en PHP avec SymfonyMieux Développer en PHP avec Symfony
Mieux Développer en PHP avec Symfony
Hugo Hamon
 
Introduction à Symfony2
Introduction à Symfony2Introduction à Symfony2
Introduction à Symfony2
Hugo Hamon
 
Exposer des services web SOAP et REST avec symfony 1.4 et Zend Framework
Exposer des services web SOAP et REST avec symfony 1.4 et Zend FrameworkExposer des services web SOAP et REST avec symfony 1.4 et Zend Framework
Exposer des services web SOAP et REST avec symfony 1.4 et Zend Framework
Hugo Hamon
 

More from Hugo Hamon (6)

Intégration Continue PHP avec Jenkins CI
Intégration Continue PHP avec Jenkins CIIntégration Continue PHP avec Jenkins CI
Intégration Continue PHP avec Jenkins CI
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Intégration continue des projets PHP avec Jenkins
Intégration continue des projets PHP avec JenkinsIntégration continue des projets PHP avec Jenkins
Intégration continue des projets PHP avec Jenkins
 
Mieux Développer en PHP avec Symfony
Mieux Développer en PHP avec SymfonyMieux Développer en PHP avec Symfony
Mieux Développer en PHP avec Symfony
 
Introduction à Symfony2
Introduction à Symfony2Introduction à Symfony2
Introduction à Symfony2
 
Exposer des services web SOAP et REST avec symfony 1.4 et Zend Framework
Exposer des services web SOAP et REST avec symfony 1.4 et Zend FrameworkExposer des services web SOAP et REST avec symfony 1.4 et Zend Framework
Exposer des services web SOAP et REST avec symfony 1.4 et Zend Framework
 

Recently uploaded

Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSECHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
kumarjarun2010
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdfARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
Inglês no Mundo Digital
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
BrainSell Technologies
 
Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...
chetankumar9855
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Networks
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Torry Harris
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
SynapseIndia
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
Priyanka Aash
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
Yevgen Sysoyev
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
bhumivarma35300
 
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAIApplying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
ssuserd4e0d2
 
Salesforce AI & Einstein Copilot Workshop
Salesforce AI & Einstein Copilot WorkshopSalesforce AI & Einstein Copilot Workshop
Salesforce AI & Einstein Copilot Workshop
CEPTES Software Inc
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
Lidia A.
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
aslasdfmkhan4750
 

Recently uploaded (20)

Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSECHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
CHAPTER-8 COMPONENTS OF COMPUTER SYSTEM CLASS 9 CBSE
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdfARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
ARTIFICIAL INTELLIGENCE (AI) IN MUSIC.pdf
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
 
Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...Amul milk launches in US: Key details of its new products ...
Amul milk launches in US: Key details of its new products ...
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
 
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...Evolution of iPaaS - simplify IT workloads to provide a unified view of  data...
Evolution of iPaaS - simplify IT workloads to provide a unified view of data...
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
 
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAIApplying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
Applying Retrieval-Augmented Generation (RAG) to Combat Hallucinations in GenAI
 
Salesforce AI & Einstein Copilot Workshop
Salesforce AI & Einstein Copilot WorkshopSalesforce AI & Einstein Copilot Workshop
Salesforce AI & Einstein Copilot Workshop
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
 

The History of PHPersistence

  • 2. The History of PHPersistence Hugo Hamon - @hhamon OSIDays November 2011
  • 6. $fp = fopen("/counter.txt","w+"); $counter = fgets($fp,1024); $counter++; fputs($fp, $counter); fclose($fp);  
  • 8. $db = mysql_connect("localhost", "root", "secret"); $name = "bob"; $result = mysql( $db, "select * from table where firstname='$name'" ); $num = mysql_numrows($result); echo "$num records found!<p>";
  • 9. $i=0; while ($i<$num); echo mysql_result($result,$i,"lcase(fullname)"); echo "n"; echo mysql_result($result,$i,"address"); echo "n"; $i++; endwhile;
  • 12. function db_connect($database, $host, $user, $pwd); function db_fetch_single($dbh, $query); function db_fetch_all($dbh, $query); function db_insert($dbh, $table, $values); function db_update($dbh, $table, $values, $pk); function db_delete($dbh, $table, $pk); function db_list_fields($dbh, $table); function db_drop_table($dbh, $table);
  • 13. function db_connect($database, $host, $user, $pwd) { $dbh = mysql_connect($host, $user, $pwd); if (!$dbh) { die('Server unavailable: '. mysql_error()); } if (!mysql_select_db($database, $dbh)) { die("'$database' unavailable: ". mysql_error()); } return $dbh; }
  • 14. /** * Fetches a single record from a database * * @param resource $dbh The database handler * @param string $query A SQL query * @return array A single record as an array */ function db_fetch_single($dbh, $query) { return current(db_fetch_all($dbh, $query)); }
  • 15. function db_fetch_all($dbh, $query) { $result = mysql_query($query, $dbh); if (!$result) { die('Invalid query: '. mysql_error()); } $records = array(); while ($record = mysql_fetch_assoc($result)) { $records[] = $record; } return $records; }
  • 16. function db_insert($dbh, $table, array $values) { $data = array(); foreach ($values as $value) { $data[] = mysql_real_escape_string($value, $dbh); } $sql = sprintf("INSERT INTO `$table` (`%s`) VALUES ('%s')", implode('`, `', array_keys($values)), implode("', '", $data) ); $result = mysql_query($query, $dbh); if (!$result) { die('Invalid data to insert: '. mysql_error()); } return mysql_insert_id($dbh); }
  • 17. include 'lib/database.inc.php'; $dbh = db_connect('osidays'); $query = 'SELECT id, name FROM author'; $authors = db_fetch_all($dbh, $query); $author = db_fetch_single( $dbh, 'SELECT id, name FROM author WHERE id = 3' ); $id = db_insert($dbh, 'author', array( 'name' => 'Jules Verne' ));
  • 18. PHP 4 OOP & Reusability
  • 19. class Database { function Database($database, host, $user, $pwd); function disconnect(); function connect(); function free(); function getErrorMessage(); function getErrorCode(); function getLastInsertId(); function insert($table, array $values); function fetchAll($query); function fetchSingle($query); function query($query); function quote($string); function hasError(); function _collectError(); function _init(); }
  • 20. require 'lib/Database.php'; $db= &new Database('demo', 'localhost', 'root'); $q = 'SELECT id, name FROM author'; foreach ($db->fetchAll($q) as $author) { // ... } $db->free(); $db->disconnect();
  • 21. require 'lib/Database.php'; $db= &new Database('demo', 'localhost', 'root'); $q = 'SELECT id, name FROM author WHERE id = 1'; $author = $db->fetchSingle($q); $db->free(); $db->disconnect();
  • 22. require 'lib/Database.php'; $db= &new Database('demo', 'localhost', 'root'); $res = $db->insert('author', array( 'name' => 'Jules Vernes' )); if ($result) { $id = $db->getLastInsertId(); } $db->disconnect();
  • 24. DBAL
  • 25. • PEAR::DB • MDB • ADOdb • MDB2 • Metabase • Creole
  • 26. §  Multiple databases support §  Uni ed APIs §  Prepared statements supports §  Query caching §  Security against SQL Injections
  • 28. $dsn = array( 'phptype' => 'mysql', 'username' => 'root', 'password' => '', 'hostspec' => 'localhost', 'database' => 'demo', ); $db = & MDB2::connect($dsn); $db->setFetchMode(MDB2_FETCHMODE_ASSOC); $rs = $db->queryAll('SELECT id, name FROM author'); $db->disconnect();
  • 29. ADOdb
  • 30. include('adodb.inc.php'); $db = NewADOConnection('mysql'); $db->Connect('localhost', 'root', 'password', 'demo'); $result = $db->Execute('SELECT id, name FROM author'); if ($result) { while (!$result->EOF) { echo 'ID: ', $result->fields[0] ,"n"; echo 'Name:', $result->fields[1] ,"n"; $result->MoveNext(); } }
  • 33. •  PECL extension as of PHP 5.0.0 •  Core extension since PHP 5.1.0 (11/2005) •  12 official drivers as of today •  Extensible Object Oriented API •  Prepared statements & transaction support •  Stored procedures support
  • 35. « PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. »
  • 36. « PDO does not provide a database abstraction as it doesn't rewrite SQL or emulate missing features »
  • 37. Transactions / Prepared Statements
  • 38. try { $pdo->beginTransaction(); $query = 'INSERT INTO author (name) VALUES (?)'; $stmt = $pdo->prepare($query); $stmt->bindValue(1, 'Jules Verne'); $stmt->execute(); $id = $pdo->lastInsertId(); $pdo->commit(); } catch (PDOException $e) { $pdo->rollback(); }
  • 40. DELIMITER | CREATE PROCEDURE coming_events (IN start DATE, OUT events INT) BEGIN SELECT COUNT(*) INTO events FROM events WHERE start_at >= start; END | $query = "CALL coming_events('2011-03-01', @events);"; $pdo->query($query); $stmt = $pdo->query("SELECT @events;"); echo $stmt->fetchColumn() ,' events to come.';
  • 43. class AuthorGateway extends Zend_Db_Table_Abstract { protected $_name = 'authors'; protected $_primary = 'author_id'; }
  • 44. $data = array( 'first_name' => 'Jules', 'last_name' => 'Vernes', ); $table = new AuthorGateway(); $table->insert($data);
  • 46. $table = new AuthorGateway(); // New empty row $row = $table->createRow(); // Insert a new row $row->firstName = 'Jules'; $row->lastName = 'Verne'; $row->save();
  • 48. $isbn = '1234567890'; $rows = $db->select() ->from(array('b' => 'books')) ->where('b.isbn = ?', $isbn) ->order(array('b.title ASC')) ->query() ->fetchAll() ;
  • 50. •  Use objects instead of raw SQL queries •  Database abstraction layer (not always) •  Relationships support •  Behaviors support (i18n, timestampable…) •  Querying API •  Error logging
  • 52. $author = new Author(); $author->setFirstName("Leo"); $author->setLastName("Tolstoy"); $book = new Book(); $book->setTitle("War & Peace"); $book->setIsbn("0140444173"); $book->setAuthor($author); $book->save();
  • 53. $query = BookQuery::create() ->joinWith('Book.Author') ->joinWith('Book.Publisher') ->where('Author.firstName = ?', 'Leo') ->where('Author.lastName = ?', 'Tolstoï') ->orderByTitle() ->filterByPublishYear(2009) ->find() ;
  • 55. $books = Doctrine_Query::create() ->select('b.*, a.*, p.*') ->from('Book b') ->leftJoin('b.Author a') ->leftJoin('b.Publisher p') ->where('a.firstName = ?', 'Karl') ->andWhere('a.lastName = ?', 'Marx') ->orderBy('b.title ASC') ->execute() ;
  • 56. 2009     PHP  5.3  
  • 59. •  Database Abstraction Layer •  Object Relational Mapping •  Schema management •  Migrations support •  XML & NoSQL databases support
  • 60. /** @Entity() */ class Author { /** * @Id() * @GeneratedValue() * @Column(type="integer") */ private $id; /** @Column(type="string", length="30") */ private $name; /** @ReferenceMany(targetDocument="BlogPost") */ private $posts = array(); }
  • 61. $post = new BlogPost(); $post->setTitle('My First Blog Post'); $post->setBody('Some content...'); $author = new Author(); $author->setName('Hugo Hamon'); $author->addPost($post); $em->persist($user); $em->persist($post); $dm->flush();
  • 63. «  Not  Only  SQL  »  
  • 64. Key abcdef   Hugo  Hamon   Value
  • 65. FirstName:  Hugo   Column 1 Key abcdef   LastName:  Hamon   Column 2 Role:  Speaker   Column 3
  • 66. Document Key abcdef   Name:  Hugo  Hamon   0:  PHP   Skills   1:  HTML   2:  CSS   Role:  Speaker  
  • 68. •  Cross-platform support •  Schemaless language •  BSON type support •  Binary le storage support (GridFS) •  Master – slave replication support •  Sharding (horizontal scaling)
  • 69. $mongo = new Mongo(); $col = $mongo->selectDb('osidays')->books; $books = array( array('title' => 'Da Vinci Code'), array('title' => 'The Lost Symbol'), array('title' => 'Digital Fortress'), ); foreach ($books as $book) { $collection->insert($book); }
  • 70. What’s next… … for today and tomorrow?
  • 71. 2011 PHP 5.3 ODM Frameworks
  • 73. •  ORM Layers for Mongodb •  Dealing with objects instead of arrays •  Relationships support •  Query abstraction •  GridFS support •  Query logging & caching
  • 74. $post = new BlogPost(); $post->setTitle('My First Blog Post'); $post->setBody('Some content...'); $author = new Author(); $author->setName('Hugo Hamon'); $author->setEmail('hugo@example.com'); $dm->persist($user); $user->addPost($post); $dm->flush();
  • 75. QuesAons?   92-98, boulevard Victor Hugo 92 115 Clichy Cedex trainings@sensio.com (+33 (0)1 40 99 82 11) sensiolabs.com - symfony.com – trainings.sensiolabs.com