Skip to content
Jason Napolitano edited this page Sep 16, 2023 · 98 revisions

The aim of DatabaseFactory is to give PHP application developers a dependency-free means to securely and efficiently interact with, manage and manipulate their databases with a simple, and intuitive API. Further documentation, including a deeper look into the API can be found here.

Project Goals

  • Security:
    • DatabaseFactory is highly opinionated in one main area; security. It's built on top of the native PHP library; PDO. It uses prepared statements to ensure that your database transactions are protected and secure.
  • Efficiency
    • Using PDO at its core, DatabaseFactory aims to be as efficient as possible, where possible. This is done by issuing statements and executing queries only when needed.
  • Accessibility
    • DatabaseFactory aims to provide a simple API that works across a range of different database drivers. Using the Query Builder or the ORM (or both in conjunction with one another), you can interact with your databases with ease.
  • Modularity
    • This library is intended to be manipulated and extended with very little effort. Customizing DatabaseFactory is extremely simple and gives developers full control over the API.
  • Documentation
    • DatabaseFactory aims to be well documented. The main repository contains a Wiki section, which contains the libraries corresponding documentation files in markdown format.

Requirements

  • PHP >=8.2
    • This package uses explicit false return types [read more] and readonly classes [read more]
  • PDO Extension

Library Features

  • Object Relational Mapper (ORM)
  • Intuitive query builder
  • Entity based system
  • Modular design

Getting Started

Installation

The first thing you'll need to do, is ensure that you have DatabaseFactory properly installed. Since DatabaseFactory requires PSR-4 to allow for proper class autoloading, composer will need to be installed within your development environment. Composer is free, and easy to install.

$ composer require database-factory/framework

Configure

When configuring DatabaseFactory, it's important to understand how it connects to a database. DatabaseFactory uses a .env file to load your credentials. Here is an example .env configuration for a MySQL based setup.

DB_HOSTNAME=127.0.0.1
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=password
DB_DRIVER=mysql

Initialize

DatabaseFactory is extremely easy to set up. Ultimately, it can be instantiated with just two lines of code. It is worth noting, that if you have a loaded env file, and your application is already connected to your database via PDO, you need'nt perform the initialization.

# first, we load the ENV configuration variables. This step is optional if
# you've already setup an ENV library for use within your project and have
# your env variables configured. 
DatabaseFactory\Facades\Env::init(__DIR__); // the absolute path of the .env file

# next, we establish a new connection. If you have already established a PDO connection 
# in your application, you can skip this step.
DatabaseFactory\Facades\DB::connect();

That's it! Now, all we need to do, is use DatabaseFactory within our application.

TLDR

The TLDR of the entire wiki boils down to this; There are three main components of DatabaseFactory - the query builder, the ORM and the Entity system. Let's take a shallow dive into how to use each of these components.

Using the query builder

DatabaseFactory provides a simple, robust and intuitive Query Builder API that grants us the ability to easily work with our database tables. In order to utilize it, we need to call the table() method or use the db_factory() helper function, and pass through the database table we want to work with.

# initiate the query builder using the facade system
$users = DatabaseFactory\Facades\DB::table('users');

# OR

# initiate the query builder using the helper function
$users = db_factory('users');
# generate the query
$users->select('name, email')->get();
# the SQL to be executed
SELECT name, email FROM users
# generate the query
$users->select('name, email')
      ->where('name', '=', 'Mark')
      ->orderBy('name', 'DESC')
      ->limit(10)
      ->get();
# the SQL to be executed
SELECT name, email FROM users WHERE name = 'Mark' ORDER BY users.name DESC LIMIT 10

Using the ORM

DatabaseFactory also provides an intuitive ORM (Object Relational Mapper) to work with data which uses an entity class to model that data (see here). The ORM has many shortcut methods which give us the ability to generate our queries with minimal code.

Selecting all columns [default behavior]

# generate the query
User::where('name', '<>', '');
# the SQL to be executed
SELECT * FROM users WHERE users.name <> ''

Selecting other columns by passing them as a string via the final argument (optional)

# generate the query
User::where('name', '<>', '', 'email, name');
# the SQL to be executed
SELECT email, name FROM users WHERE users.name <> ''

Using them together

Naturally, you can use the ORM and Query Builder in conjunction with one another to build complex queries, by calling the query() method.

Selecting all columns [default behavior]

# generate the query
User::query()->select()->where('name', '<>', '')->get()
# the SQL to be executed
SELECT * FROM users WHERE users.name <> ''

Using Entities

DatabaseFactory uses the entity system to model data. To get the skinny on how DatabaseFactory uses entities, check out the Entities section of the wiki by going here. The Entities section is a prerequisite for the section you are currently reading.

Creating data

Creating new data and adding it to your database is extremely simple. All we need to do is create a new entity object, and assign values to its fields. From there, we call the save() method to save the record.

# create a new entity object
$user = new User();

# assign values to the entities properties
$user->name = 'Georges St. Pierre';
$user->email = 'gsp_is_goat@gmail.com';

# save the record
$user->save();

Modifying data

Updating a record is virtually identical to creating a new one. The main difference here is that we will be passing an ID into the constructor of the entity object which represents the record we are working with

# create a new entity object and pass the ID 
# into the constructor
$user = new User(15);

# assign values to the entities properties
$user->name = 'Anderson Silva';
$user->email = 'silva_is_goat@gmail.com';

# save the record
$user->save();

Deleting data

To delete a record, we will need to create a new entity object and pass the ID of the record we'd like to delete, into the constructor. From there, we simply call the delete() method to delete that record from storage.

# create a new entity object and pass the ID
# into the constructor
$user = new User(15);

# delete the record
$user->delete();