The Factory pattern in PHP

The Factory pattern is a popular design pattern used in many languages.

It's relatively simple on the surface. You have a set of method that create objects, usually in a state ready to use without setting them up manually.

The Example using static methods

class MyFactory
    public static function getUser(int $user_id) : ?User
        $user_details = getUserDetails();

        if($user_details === null) return null;

        $user = new User();
        $user->user_name = $user_details['user_name'];
        // Etc.

        return $user;

    /// Etc...

The idea is simple. Use methods to create the objects you need. It can save a lot of hassle when there is a complex system with many objects.


The factory pattern is great in most circumstances but it often can't deal with the situational edge cases, so it's wise to bare this in mind.

It's also very easy to create many factory methods that never get used or could be combined into a single method.

The Benfits

The factory pattern abstracts away from setting up objects, leaving the logic that set's them up hidden within the factory methods. This can improve development speed and reduce complexity.

It also gives you the benefit of descriptive naming to improve the understandability of your code.

Written by Kieran on 2019-08-11
This website uses Cookies to enhance your experience. Close Manage