How To Create a PHP Factory Pattern

Creating an MVC has helped me learn a lot of new programming concepts. Amongst them is something called a factory pattern. Programming patterns are not required – They are simply best practices to solving certain problems. That means that although it is possible to solve the same problem using alternative methods, a pattern will be the most efficient way to achieve your goal.

Today I’ll be looking at the Factory Pattern. In real life, a factory creates items. Similarly, in a factory pattern, the ‘factory’ will create objects.

Creating a Factory Pattern

To explain this, let me show you how we normally create an object and use it:

<?php
$oUser = new User();
$oUser->start();
?>

The code above creates a User object and calls the start function. The factory pattern gives you a way of doing this in just one line.

Here’s how.

<?php
class User
{
    public static function factory()
    {
        return new __CLASS__;
    }
    public function start() { ... }
}

User::factory()->start();
?>

The factory function above is creating and returning an object. __CLASS__ is a magic constant which stores the class name and in this case will store “User”. Thus, the factory function will return a new User object.

It is very important to note that this function must be static and can be called anything you wish (not just factory).

By returning the object, we can now do some simple method chaining and keep it all in one line.

Why would you use it?

Of course, you can also use the factory pattern to create a factory class which is responsible for creating all objects of all classes (not just its own). In this case, you would pass the class name as a parameter to the factory function which will then create an object based on that name.

Have a look at the example below.

<?php
class Builder
{
    public static function factory($sClassName)
    {
        return new $sClassName;
    }
}

$oUser = Builder::factory("User");
?>

While you might struggle to see how this pattern can be useful, keep in mind that patterns are simply ways to make your life easier. If you’re dealing with objects and classes, you will eventually come across a situation which in which the factory pattern would work perfectly.

Factory patterns will be particularly useful when you want to initialize an object differently based on the state of other objects or classes. In such cases, the factory class can take care of initializing it the right way. Another reason would be to auto load the right files based on the object you want to initialize.

To learn more about factory patterns, I would definitely recommend checking out the official PHP documentation. If you have any questions, feel free to leave a comment.

Don't forget to check out more posts from the Tutorial of the Week section.

blog comments powered by Disqus
.