Factory Pattern
What Is It?
The Factory Pattern provides an interface for creating objects without specifying their exact class. The creation logic is centralized in a factory method or class.
Why?
Creating objects directly with new ties code to specific implementations. Factories abstract creation, making it easy to swap implementations or add creation logic.
When to Use
When object creation is complex, when you need to create different types based on input, when you want to centralize creation logic for testing.
When Not to Use
Simple object creation with no variation. When there's only one implementation. When the factory logic is trivial.
Example
Example
<?php
// Factory interface
interface NotificationFactory
{
public function create(string $channel): NotificationInterface;
}
// Concrete factory
class NotificationFactoryImpl implements NotificationFactory
{
public function __construct(
private Mailer $mailer,
private TwilioClient $twilio,
private PushNotificationService $push
) {}
public function create(string $channel): NotificationInterface
{
return match ($channel) {
'email' => new EmailNotification($this->mailer),
'sms' => new SmsNotification($this->twilio),
'push' => new PushNotification($this->push),
default => throw new \InvalidArgumentException("Unknown channel: {$channel}")
};
}
}
// Laravel Model Factories (built-in factory pattern)
class PostFactory extends Factory
{
public function definition(): array
{
return [
'title' => fake()->sentence(),
'slug' => fake()->unique()->slug(),
'body' => fake()->paragraphs(3, true),
'user_id' => User::factory(),
];
}
public function published(): static
{
return $this->state(fn () => ['published_at' => fake()->dateTimeBetween('-1 year')]);
}
}
// Usage
Post::factory()->count(10)->published()->create();
Pros
- Centralized object creation
- Easy to swap implementations
- Simplifies testing (mock the factory)
- Follows Open/Closed principle
- Laravel has built-in model factories
Cons
- Additional classes/interfaces
- Can become complex with many types
- May be overkill for simple creation
- Factory proliferation in large applications