以下のソースコードは単一責任の原則に反しています。
1つのクラスで以下の異なる責務を担当しているため、単一の責任に集中していない状態です。
<?php
class User
{
private string $userName;
private string $email;
public function __construct(string $userName, string $email)
{
$this->userName = $userName;
$this->email = $email;
}
public function getUserName(): string
{
return $this->userName;
}
public function getEmail(): string
{
return $this->email;
}
public function login()
{
// ログイン処理
// ...
}
public function logout()
{
// ログアウト処理
// ...
}
public function makePayment()
{
// 支払い処理
// ...
}
}
単一責任の原則の則りリファクタリングを行うと下記のようになります。
このように、各クラスは単一の責務に焦点を当て、個別の機能を提供することで、単一責任の原則が満たされています。
各クラスが明確で独立した責務を持つため、コードの理解と保守が容易になり、変更や修正がしやすくなります。
<?php
class UserProfile
{
private string $userName;
private string $email;
public function __construct(string $userName, string $email)
{
$this->userName = $userName;
$this->email = $email;
}
public function getUserName(): string
{
return $this->userName;
}
public function getEmail(): string
{
return $this->email;
}
}
<?php
class Auth
{
public function login(string $userName, string $password)
{
// ログイン処理
// ...
}
public function logout()
{
// ログアウト処理
// ...
}
}
<?php
class UserPayment
{
public function makePayment($amount)
{
// 支払い処理
// ...
}
}