SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
A Database Factory for PHP
           http://phactory.org

                                                    Chris Kite
                               Sr. Web Engineer at Offers.com
© 2009 Vertive, Inc.
Proprietary and Confidential                        @chriskite
Phactory: What is it?

Alternative to database fixtures for unit
 tests
Define and create objects in code
Provides a lightweight ORM
Works with MySQL, SQLite, and
 MongoDB



     © 2009 Vertive, Inc.
     Proprietary and Confidential
Phactory is developed and used at
            Offers.com
Databases in Unit Testing


  © 2009 Vertive, Inc.
  Proprietary and Confidential
Database Fixtures

A fixture is a statically defined set of data
Each test can have its own dataset
PHPUnit provides support for loading
 fixtures:
  class DatabaseTest extends PHPUnit_Extensions_Database_TestCase
  {
     protected function getConnection()
     {
       $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', '');
       return $this->createDefaultDBConnection($pdo, 'testdb');
     }

      protected function getDataSet()
      {
        return $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/bank-account-seed.xml');
      }
  }

          © 2009 Vertive, Inc.
          Proprietary and Confidential
Database Fixtures
<?xml version="1.0" encoding="UTF-8" ?>
<dataset>
  <post
     post_id="1"
     title="My First Post"
     date_created="2008-12-01 12:30:29"
     contents="This is my first post" rating="5"
  />
 <post
     post_id="2"
     title="My Second Post"
     date_created="2008-12-04 15:35:25"
     contents="This is my second post"
  />
</dataset> Vertive, Inc.
        © 2009
       Proprietary and Confidential   Example from http://www.phpunit.de/manual/current/en/database.html
Database Fixtures

Drawbacks:
  » Typically in an unfriendly format like XML
  » You are left to your own devices to retrieve
    and manipulate data in your test
  » Can’t dynamically create objects
  » No concept of associations




     © 2009 Vertive, Inc.
     Proprietary and Confidential
Database Factories

Define database test data in code, not flat
 files
Create objects dynamically, rather than
 loading them all at once
Define associations between objects
Can integrate with or provide ORM
 functionality


     © 2009 Vertive, Inc.
     Proprietary and Confidential
Database Factories
Phactory Example
<?
Phactory::setConnection(new PDO('sqlite:test.db'));

Phactory::define('user', array('name' => 'Test User',
                                'email' => 'user@example.com'));

$user = Phactory::create('user'); // creates a row in the 'users' table

print("Hello, {$user->name}!"); // prints "Hello, Test User!"




        © 2009 Vertive, Inc.
        Proprietary and Confidential
Using Phactory


  © 2009 Vertive, Inc.
  Proprietary and Confidential
Connecting to the Database

Phactory supports MySQL, SQLite, and
 MongoDB
Uses PDO for SQL databases
<?
require_once 'Phactory/lib/Phactory.php';

$pdo = new PDO('mysql:host=127.0.0.1; dbname=testdb', 'user', 'password');

Phactory::setConnection($pdo);




         © 2009 Vertive, Inc.
         Proprietary and Confidential
Defining Table Blueprints

A blueprint defines default values for
 objects created in a particular table
<?
Phactory::define('user', array('name' => 'test_user',
                        'age' => 20));

Phactory::define('post', array('text' => 'This is a post',
                       'created_at' => 1296663323));




         © 2009 Vertive, Inc.
         Proprietary and Confidential
Creating Objects

When creating an object with Phactory,
 you can:
  » Specify values for fields that weren’t in the
    blueprint definition
  » Override any of the default values
  » Associate with other objects




     © 2009 Vertive, Inc.
     Proprietary and Confidential
Creating Objects
Phactory::define('user', array('name' => 'test_user', 'age' => 20));

$john = Phactory::create('user', array('name' => 'John Doe'));
$joe = Phactory::create('user', array('name' => 'Joe Smith', 'activated' => 1));
$anon = Phactory::create('user');

// $john looks like this:
$john->id == 1;
$john->name == 'John Doe';
$john->activated == 0;

// $joe looks like this:
$joe->id == 2;
$joe->name == 'Joe Smith';
$joe->activated == 1;

// $anon looks like this:
$anon->id == 3;
$anon->name == 'test_user';
$anon->activated == 0;
           © 2009 Vertive, Inc.
           Proprietary and Confidential
Retrieving Objects

Basic ORM functionality allows you to
 retrieve Phactory objects from the
 database
Uses a simple get() method which takes
 an array of columns to match
$joe = Phactory::get('user', array('id' => 2));

$joe = Phactory::get('user', array('age' => 20, 'activated' => 1));



        © 2009 Vertive, Inc.
        Proprietary and Confidential
Associations

For SQL databases, Phactory provides
 many-to-one and many-to-many
 associations
Foreign key columns and join tables are
 filled in automatically when creating an
 object with associations



     © 2009 Vertive, Inc.
     Proprietary and Confidential
Associations
Phactory::define('author');

Phactory::define('book',
           array('name' => 'Test Book'),
           array('primary_author' => Phactory::manyToOne('author')));

$twain = Phactory::create('author', array('name' => 'Mark Twain'));

$book = Phactory::createWithAssociations('book', array('primary_author'
=> $twain));

$book->author_id == $twain->getId();




          © 2009 Vertive, Inc.
          Proprietary and Confidential
Sequences

Define blueprints with automatically
 incrementing values
   » Include ‘$n’ in the definition
   » Sequence starts at 0, and is incremented
     each time an object is created
Phactory::define('user', array('name' => 'user$n', 'age' => '$n'));

$user0 = Phactory::create('user'); // name == 'user0', age == '0'
$user1 = Phactory::create('user'); // name == 'user1', age == '1'
$user2 = Phactory::create('user'); // name == 'user2', age == '2'


        © 2009 Vertive, Inc.
        Proprietary and Confidential
Phactory and PHPUnit


  © 2009 Vertive, Inc.
  Proprietary and Confidential
Basic Test Setup
require_once 'Phactory/lib/Phactory.php';
class ExampleTest extends PHPUnit_Framework_TestCase
{
   public static function setUpBeforeClass()
   {
     // create a db connection and tell Phactory to use it
     $pdo = new PDO("sqlite:test.db");
     Phactory::setConnection($pdo);

      // reset any existing blueprints and empty any tables Phactory has used
      Phactory::reset();

      // define default values for each user we will create
      Phactory::define('user', array('name' => 'Test User $n', 'age' => 18));
  }

  public static function tearDownAfterClass()
  {
    Phactory::reset();
  }

  public function tearDown()
  {
       // delete all objects from defined tables, but do not erase blueprints
       Phactory::recall();
  }
               © 2009 Vertive, Inc.
               Proprietary and Confidential
Structuring Shared Definitions

Usually many of the test classes in your
 suite will need to use the same tables
Define blueprints in one place, share them
 among many tests
  » Can include() a file of definitions, put
    definitions in a static class, etc.




     © 2009 Vertive, Inc.
     Proprietary and Confidential
Structuring Shared Definitions
SharedDefinitions.php
<?
Phactory::define('tag', array('name' => 'Tag $n'));

Phactory::define('post',
           array('name' => 'Test Blog Post', 'content' => 'Test Content'),
           array('tag' => Phactory::manyToMany('tag', 'posts_tags')));



ExampleTest.php
class ExampleTest extends PHPUnit_Framework_TestCase
{
   public static function setUpBeforeClass()
   {
     $pdo = new PDO("sqlite:test.db");
     Phactory::setConnection($pdo);
     Phactory::reset();

        // include definitions common to several tests
        include('SharedDefinitions.php');
    }
}

                © 2009 Vertive, Inc.
                Proprietary and Confidential
Dynamic Objects

Recall that with fixtures, your test data is
 all loaded at the start of the test
With Phactory, you can create or change
 test data during a test




     © 2009 Vertive, Inc.
     Proprietary and Confidential
Dynamic Objects
class MyPostClass {
      public static function countTagsForPost($post_id) {
            $stmt = $pdo->prepare("SELECT COUNT(*) AS num_tags
                                     FROM `posts_tags` WHERE `post_id` = ?");
            $stmt->execute(array($post_id));
            $result = $stmt->fetch();
            return $result['num_tags'];
      }
}

Phactory::define('tag',
             array('name' => 'Tag $n'),
             array('post' => Phactory::manyToMany('post', 'posts_tags')));

Phactory::define('post',
           array('name' => 'Test Blog Post', 'content' => 'Test Content'),
           array('tag' => Phactory::manyToMany('tag', 'posts_tags')));

$post = Phactory::create('post');

$this->assertEquals(0, MyPostClass::countTagsForPost($post->getId()));
$tag = Phactory::createWithAssociations('tag', array('post' => $post));
          © 2009 Vertive, Inc.
$this->assertEquals(1, MyPostClass::countTagsForPost($post->getId()));
          Proprietary and Confidential
Using Phactory with MongoDB

 require_once 'Phactory/lib/PhactoryMongo.php';

 Uses the Mongo PHP driver
 Almost exactly the same as regular SQL
  Phactory, except:
   » Documents returned as arrays rather than
     Phactory_Row objects
   » Phactory::get() supports all Mongo queries
   » Associations: embedsOne and embedsMany
 http://phactory.org/mongodb-guide/

       © 2009 Vertive, Inc.
       Proprietary and Confidential
QUESTIONS


  © 2009 Vertive, Inc.
  Proprietary and Confidential
Thank You!

These slides are online at
 http://bit.ly/PhactoryWebinar

Contact me on Twitter: @chriskite

Visit http://phactory.org to download and
 for more information

     © 2009 Vertive, Inc.
     Proprietary and Confidential
Phactory
Phactory

Más contenido relacionado

Was ist angesagt?

Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Fabien Potencier
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friendkikoalonsob
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data ObjectsWez Furlong
 
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 mockingKonstantin Kudryashov
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in LaravelHAO-WEN ZHANG
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalFredric Mitchell
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperJonathan Wage
 
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 EditionNate Abele
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMJonathan Wage
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介Jace Ju
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010Fabien Potencier
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
Rails' Next Top Model
Rails' Next Top ModelRails' Next Top Model
Rails' Next Top ModelAdam Keys
 
Introduction to DI(C)
Introduction to DI(C)Introduction to DI(C)
Introduction to DI(C)Radek Benkel
 

Was ist angesagt? (20)

Presentation1
Presentation1Presentation1
Presentation1
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friend
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
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
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
 
Deep dive into Oracle ADF
Deep dive into Oracle ADFDeep dive into Oracle ADF
Deep dive into Oracle ADF
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in Drupal
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
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
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Rails' Next Top Model
Rails' Next Top ModelRails' Next Top Model
Rails' Next Top Model
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Introduction to DI(C)
Introduction to DI(C)Introduction to DI(C)
Introduction to DI(C)
 

Andere mochten auch

Andere mochten auch (8)

Prueba
PruebaPrueba
Prueba
 
Doctrine2
Doctrine2Doctrine2
Doctrine2
 
Manual doctrine jog
Manual doctrine jogManual doctrine jog
Manual doctrine jog
 
Susferrin diseno elementos_maquinas
Susferrin diseno elementos_maquinasSusferrin diseno elementos_maquinas
Susferrin diseno elementos_maquinas
 
Configuracion de mysql
Configuracion de mysqlConfiguracion de mysql
Configuracion de mysql
 
Configuracion de mysql
Configuracion de mysqlConfiguracion de mysql
Configuracion de mysql
 
Doctrine2 enterpice
Doctrine2 enterpiceDoctrine2 enterpice
Doctrine2 enterpice
 
Law of sine and cosines
Law of sine and cosinesLaw of sine and cosines
Law of sine and cosines
 

Ähnlich wie Phactory

Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Part 2
Part 2Part 2
Part 2A VD
 
Nashville Symfony Functional Testing
Nashville Symfony Functional TestingNashville Symfony Functional Testing
Nashville Symfony Functional TestingBrent Shaffer
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityWashington Botelho
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsMichael Peacock
 
Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014Eric Hogue
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013Michelangelo van Dam
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitPeter Wilcsinszky
 
Rapid Prototyping with PEAR
Rapid Prototyping with PEARRapid Prototyping with PEAR
Rapid Prototyping with PEARMarkus Wolff
 

Ähnlich wie Phactory (20)

Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Part 2
Part 2Part 2
Part 2
 
Nashville Symfony Functional Testing
Nashville Symfony Functional TestingNashville Symfony Functional Testing
Nashville Symfony Functional Testing
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014
 
Q
QQ
Q
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
 
Rapid Prototyping with PEAR
Rapid Prototyping with PEARRapid Prototyping with PEAR
Rapid Prototyping with PEAR
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 

Último

Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxSatishbabu Gunukula
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameKapil Thakar
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTxtailishbaloch
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationKnoldus Inc.
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kitJamie (Taka) Wang
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxGraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxNeo4j
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updateadam112203
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Alkin Tezuysal
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0DanBrown980551
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024Brian Pichman
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024Brian Pichman
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechProduct School
 
.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptxHansamali Gamage
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInThousandEyes
 
The New Cloud World Order Is FinOps (Slideshow)
The New Cloud World Order Is FinOps (Slideshow)The New Cloud World Order Is FinOps (Slideshow)
The New Cloud World Order Is FinOps (Slideshow)codyslingerland1
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdfThe Good Food Institute
 

Último (20)

Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptx
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First Frame
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its application
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kit
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxGraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 update
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024AI Workshops at Computers In Libraries 2024
AI Workshops at Computers In Libraries 2024
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
 
.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
 
The New Cloud World Order Is FinOps (Slideshow)
The New Cloud World Order Is FinOps (Slideshow)The New Cloud World Order Is FinOps (Slideshow)
The New Cloud World Order Is FinOps (Slideshow)
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf
 

Phactory

  • 1. A Database Factory for PHP http://phactory.org Chris Kite Sr. Web Engineer at Offers.com © 2009 Vertive, Inc. Proprietary and Confidential @chriskite
  • 2. Phactory: What is it? Alternative to database fixtures for unit tests Define and create objects in code Provides a lightweight ORM Works with MySQL, SQLite, and MongoDB © 2009 Vertive, Inc. Proprietary and Confidential
  • 3. Phactory is developed and used at Offers.com
  • 4. Databases in Unit Testing © 2009 Vertive, Inc. Proprietary and Confidential
  • 5. Database Fixtures A fixture is a statically defined set of data Each test can have its own dataset PHPUnit provides support for loading fixtures: class DatabaseTest extends PHPUnit_Extensions_Database_TestCase { protected function getConnection() { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', ''); return $this->createDefaultDBConnection($pdo, 'testdb'); } protected function getDataSet() { return $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/bank-account-seed.xml'); } } © 2009 Vertive, Inc. Proprietary and Confidential
  • 6. Database Fixtures <?xml version="1.0" encoding="UTF-8" ?> <dataset> <post post_id="1" title="My First Post" date_created="2008-12-01 12:30:29" contents="This is my first post" rating="5" /> <post post_id="2" title="My Second Post" date_created="2008-12-04 15:35:25" contents="This is my second post" /> </dataset> Vertive, Inc. © 2009 Proprietary and Confidential Example from http://www.phpunit.de/manual/current/en/database.html
  • 7. Database Fixtures Drawbacks: » Typically in an unfriendly format like XML » You are left to your own devices to retrieve and manipulate data in your test » Can’t dynamically create objects » No concept of associations © 2009 Vertive, Inc. Proprietary and Confidential
  • 8. Database Factories Define database test data in code, not flat files Create objects dynamically, rather than loading them all at once Define associations between objects Can integrate with or provide ORM functionality © 2009 Vertive, Inc. Proprietary and Confidential
  • 9. Database Factories Phactory Example <? Phactory::setConnection(new PDO('sqlite:test.db')); Phactory::define('user', array('name' => 'Test User', 'email' => 'user@example.com')); $user = Phactory::create('user'); // creates a row in the 'users' table print("Hello, {$user->name}!"); // prints "Hello, Test User!" © 2009 Vertive, Inc. Proprietary and Confidential
  • 10. Using Phactory © 2009 Vertive, Inc. Proprietary and Confidential
  • 11. Connecting to the Database Phactory supports MySQL, SQLite, and MongoDB Uses PDO for SQL databases <? require_once 'Phactory/lib/Phactory.php'; $pdo = new PDO('mysql:host=127.0.0.1; dbname=testdb', 'user', 'password'); Phactory::setConnection($pdo); © 2009 Vertive, Inc. Proprietary and Confidential
  • 12. Defining Table Blueprints A blueprint defines default values for objects created in a particular table <? Phactory::define('user', array('name' => 'test_user', 'age' => 20)); Phactory::define('post', array('text' => 'This is a post', 'created_at' => 1296663323)); © 2009 Vertive, Inc. Proprietary and Confidential
  • 13. Creating Objects When creating an object with Phactory, you can: » Specify values for fields that weren’t in the blueprint definition » Override any of the default values » Associate with other objects © 2009 Vertive, Inc. Proprietary and Confidential
  • 14. Creating Objects Phactory::define('user', array('name' => 'test_user', 'age' => 20)); $john = Phactory::create('user', array('name' => 'John Doe')); $joe = Phactory::create('user', array('name' => 'Joe Smith', 'activated' => 1)); $anon = Phactory::create('user'); // $john looks like this: $john->id == 1; $john->name == 'John Doe'; $john->activated == 0; // $joe looks like this: $joe->id == 2; $joe->name == 'Joe Smith'; $joe->activated == 1; // $anon looks like this: $anon->id == 3; $anon->name == 'test_user'; $anon->activated == 0; © 2009 Vertive, Inc. Proprietary and Confidential
  • 15. Retrieving Objects Basic ORM functionality allows you to retrieve Phactory objects from the database Uses a simple get() method which takes an array of columns to match $joe = Phactory::get('user', array('id' => 2)); $joe = Phactory::get('user', array('age' => 20, 'activated' => 1)); © 2009 Vertive, Inc. Proprietary and Confidential
  • 16. Associations For SQL databases, Phactory provides many-to-one and many-to-many associations Foreign key columns and join tables are filled in automatically when creating an object with associations © 2009 Vertive, Inc. Proprietary and Confidential
  • 17. Associations Phactory::define('author'); Phactory::define('book', array('name' => 'Test Book'), array('primary_author' => Phactory::manyToOne('author'))); $twain = Phactory::create('author', array('name' => 'Mark Twain')); $book = Phactory::createWithAssociations('book', array('primary_author' => $twain)); $book->author_id == $twain->getId(); © 2009 Vertive, Inc. Proprietary and Confidential
  • 18. Sequences Define blueprints with automatically incrementing values » Include ‘$n’ in the definition » Sequence starts at 0, and is incremented each time an object is created Phactory::define('user', array('name' => 'user$n', 'age' => '$n')); $user0 = Phactory::create('user'); // name == 'user0', age == '0' $user1 = Phactory::create('user'); // name == 'user1', age == '1' $user2 = Phactory::create('user'); // name == 'user2', age == '2' © 2009 Vertive, Inc. Proprietary and Confidential
  • 19. Phactory and PHPUnit © 2009 Vertive, Inc. Proprietary and Confidential
  • 20. Basic Test Setup require_once 'Phactory/lib/Phactory.php'; class ExampleTest extends PHPUnit_Framework_TestCase { public static function setUpBeforeClass() { // create a db connection and tell Phactory to use it $pdo = new PDO("sqlite:test.db"); Phactory::setConnection($pdo); // reset any existing blueprints and empty any tables Phactory has used Phactory::reset(); // define default values for each user we will create Phactory::define('user', array('name' => 'Test User $n', 'age' => 18)); } public static function tearDownAfterClass() { Phactory::reset(); } public function tearDown() { // delete all objects from defined tables, but do not erase blueprints Phactory::recall(); } © 2009 Vertive, Inc. Proprietary and Confidential
  • 21. Structuring Shared Definitions Usually many of the test classes in your suite will need to use the same tables Define blueprints in one place, share them among many tests » Can include() a file of definitions, put definitions in a static class, etc. © 2009 Vertive, Inc. Proprietary and Confidential
  • 22. Structuring Shared Definitions SharedDefinitions.php <? Phactory::define('tag', array('name' => 'Tag $n')); Phactory::define('post', array('name' => 'Test Blog Post', 'content' => 'Test Content'), array('tag' => Phactory::manyToMany('tag', 'posts_tags'))); ExampleTest.php class ExampleTest extends PHPUnit_Framework_TestCase { public static function setUpBeforeClass() { $pdo = new PDO("sqlite:test.db"); Phactory::setConnection($pdo); Phactory::reset(); // include definitions common to several tests include('SharedDefinitions.php'); } } © 2009 Vertive, Inc. Proprietary and Confidential
  • 23. Dynamic Objects Recall that with fixtures, your test data is all loaded at the start of the test With Phactory, you can create or change test data during a test © 2009 Vertive, Inc. Proprietary and Confidential
  • 24. Dynamic Objects class MyPostClass { public static function countTagsForPost($post_id) { $stmt = $pdo->prepare("SELECT COUNT(*) AS num_tags FROM `posts_tags` WHERE `post_id` = ?"); $stmt->execute(array($post_id)); $result = $stmt->fetch(); return $result['num_tags']; } } Phactory::define('tag', array('name' => 'Tag $n'), array('post' => Phactory::manyToMany('post', 'posts_tags'))); Phactory::define('post', array('name' => 'Test Blog Post', 'content' => 'Test Content'), array('tag' => Phactory::manyToMany('tag', 'posts_tags'))); $post = Phactory::create('post'); $this->assertEquals(0, MyPostClass::countTagsForPost($post->getId())); $tag = Phactory::createWithAssociations('tag', array('post' => $post)); © 2009 Vertive, Inc. $this->assertEquals(1, MyPostClass::countTagsForPost($post->getId())); Proprietary and Confidential
  • 25. Using Phactory with MongoDB  require_once 'Phactory/lib/PhactoryMongo.php';  Uses the Mongo PHP driver  Almost exactly the same as regular SQL Phactory, except: » Documents returned as arrays rather than Phactory_Row objects » Phactory::get() supports all Mongo queries » Associations: embedsOne and embedsMany  http://phactory.org/mongodb-guide/ © 2009 Vertive, Inc. Proprietary and Confidential
  • 26. QUESTIONS © 2009 Vertive, Inc. Proprietary and Confidential
  • 27. Thank You! These slides are online at http://bit.ly/PhactoryWebinar Contact me on Twitter: @chriskite Visit http://phactory.org to download and for more information © 2009 Vertive, Inc. Proprietary and Confidential