The Factory Design Pattern in PHP

Published on by Dasun Tharanga

2 min read

🤔 What is it?

Let's say you're developing an e-commerce website that accepts payments from various payment gateways like PayPal, Stripe, and Square. Instead of writing code that directly interacts with each payment gateway, you create a common interface or abstraction layer that all payment gateways adhere to.

As such, the factory pattern is useful when you need to select one class within several classes at runtime.

Now you can imagine how to implement this pattern in our project. Let's dive into it. 🥽

🧪 Real-World Example

First we will creata a PaymentGateway interface. Using this interface the developer does not miss the function to declare when creating a new payment service in the future. Because any function that exists in the interface must be implemented in every class that implements this interface.

If you are not familiar with PHP interfaces, I recommend you check out this article here!

1// PaymentGateway.php
2interface PaymentGateway {
3 public function processPayment($amount);
4}

Now let's create all payment gateway service classes like below.

1// PayPalGateway.php
2class PayPalGateway implements PaymentGateway {
3 public function processPayment($amount) {
4 return "Payment of $amount processed via PayPal";
5 }
6}
1// StripeGateway.php
2class StripeGateway implements PaymentGateway {
3 public function processPayment($amount)
4 {
5 return "Payment of $amount processed via Stripe";
6 }
7}
1// SquareGateway.php
2class SquareGateway implements PaymentGateway {
3 public function processPayment($amount)
4 {
5 return "Payment of $amount processed via Square";
6 }
7}

As you can see, every payment gateway class implements the PaymentGateway interface.

Finally, we create a factory class that returns a payment gateway instance of our choice.

It's like we have a real factory that manufactures different foods and as per our request the factory will cook the food we want one by one.

1// PaymentGatewayFactory.php
2class PaymentGatewayFactory {
3 public static function make($gatewayType): PaymentGateway
4 {
5 switch ($gatewayType) {
6 case 'paypal':
7 return new PayPalGateway();
8 case 'stripe':
9 return new StripeGateway();
10 case 'square':
11 return new SquareGateway();
12 default:
13 throw new Exception("Unsupported payment gateway type: $gatewayType");
14 }
15 }
16}

Boom 💥, now you can process payments with various payment gateways.

1// Create payment gateway object using factory method
2$paymentGateway = PaymentGatewayFactory::make('paypal');
3echo $paymentGateway->processPayment(100);

You get the idea right? I hope this helps! See you in the next post!

Get notified for the next blog post? Sign up for the newsletter.