PHP Factory Method Pattern in a Blog Website
Let’s say you have a blog site that allows users to create different types of posts, such as articles, videos, and images. You want to use the Factory Method pattern to create instances of these posts, without having to know the details of how they are created.
First, you would define an interface for the post:
interface Post
{
public function publish(): void;
}
This interface defines a method called publish()
that publishes the post.
Next, you would create concrete classes that implement the Post
interface. Here's an example of a class for articles:
class Article implements Post
{
private $title;
private $content;
public function __construct(string $title, string $content)
{
$this->title = $title;
$this->content = $content;
}
public function publish(): void
{
// TODO: Implement publish() method for articles.
}
}
This class has private properties for the title and content of the article, as well as a constructor that takes these values as parameters, and an implementation of the publish()
method.
You would create similar classes for videos, images, and any other types of posts you need.
Next, you would create a factory interface for creating posts:
interface PostFactory
{
public function createPost(array $data): Post;
}
This interface defines a method called createPost()
that takes an array of data as a parameter and returns a new instance of a Post
.
Finally, you would create concrete classes that implement the PostFactory
interface for each type of post. Here's an example of a class for creating articles:
class ArticleFactory implements PostFactory
{
public function createPost(array $data): Post
{
$title = $data['title'];
$content = $data['content'];
return new Article($title, $content);
}
}
This class implements the createPost()
method that takes an array of data containing the title and content of the article, creates a new instance of the Article
class with that data, and returns it.
You would create similar classes for videos, images, and any other types of posts you need.
Here’s an example of how you could use the Factory Method pattern to create an article:
$factory = new ArticleFactory();
$data = ['title' => 'My First Article', 'content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'];
$post = $factory->createPost($data);
$post->publish();
In this example, you create a new ArticleFactory
instance, and then create an array of data containing the title and content of the article. You then call the createPost()
method on the factory, passing in the data, to create a new instance of the Article
class, and finally call the publish()
method on the post to publish it.