What is it?

Phactory is an alternative to using database fixtures in your PHP unit tests. Instead of maintaining a separate XML file of data, you define a blueprint for each table and then create as many different objects as you need in your PHP code.

By using a database factory instead of fixtures, your unit tests will be more clear and easier to write. You’ll also be able to change the objects you create programmatically instead of being stuck with the same old fixtures. Phactory also provides a simple and lightweight database ORM you can use in your tests rather than pulling in a heavy project like Doctrine.

Phactory contains two flavors: SQL and MongoDB. Most of the information on this site describes the SQL version, but the Mongo version is almost identical. You can view a detailed Phactory MongoDB guide.

How do I use it?

You can use Phactory as a database object factory with PHPUnit, SimpleTest, or any other PHP unit test framework.

After giving Phactory a database connection, you’ll define a blueprint for each table you want to create objects in. The blueprint provides default values for some or all of the columns in that table. You can then create one or more objects in that table, and optionally override the default values for each one.

Take a look at this example, which assumes you have a SQLite database with a ‘users’ table. Notice that Phactory handles the pluralization of the table name automatically.

require_once 'Phactory/lib/Phactory.php';

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!"

Who created it?

Phactory was conceived and developed by Chris Kite, Dennis Heckman, and Adrian Barrera at Offers.com.

The idea for Phactory was inspired by Thoughtbot’s Factory Girl for Ruby and Rails.