Web Development
02-02-2024

Single Responsibility Principle

Dmytro Tus
Full Stack Web developer

Bad approach:

<?php

class Mp3Player {
    public function playMusic() {
        echo 'music is playing';
        return;
    }

    public function changeTheTrack() {
        echo 'track is changed';
        return;
    }

    public function playVideo() {
        echo 'video is playing';
        return;
    }
}


$player = new Mp3Player();
$player->playMusic();
$player->playVideo();

 

Good approach

 

<?php

class Mp3Player {
    public function playMusic() {
        echo 'music is playing';
        return;
    }

    public function changeTheTrack() {
        echo 'track is changed';
        return;
    }
}

class VideoPlayer {
    public function playVideo() {
        echo 'video is playing';
        return;
    }
}


$playerMusic = new Mp3Player();
$playerMusic->playMusic();

$playerVideo = new VideoPlayer();
$playerVideo->playVideo();

Tags:

Another posts