I have table called posts in my DB. Each post has field called social_network
When I get all posts into array in my code I need to create instances for each one based on it’s social_network field.
Right now I use switch statement for this but I don’t like it as it is not flexible.
$posts = DataBase::getPosts(); // pseudocode
foreach($posts as $post) {
switch($post->getSocialNetwork()){
case 'Facebook':
$social = new FacebookPost($post->getId());
break;
case 'Twitter':
$social = new TwitterPost($post->getId());
break;
// .... other social networks
}
}
Add an interface to the classes FacebookPost and TwitterPost (eg SocialPostInterface) that has defined same basic necessary methods like
getId(),postToNetwork()Then you can add as many new social networks as you want, without having to change this piece of code. They just have to implement the interfaceThen experience the power of polymorhpism: