Single Responsibility Principle(SRP)
Kanuni hii inasema kwamba kila darasa linapaswa kuwa na jukumu moja. Inasisitiza kwamba darasa linapaswa kufanya kazi moja maalum na lisiwe na sababu nyingi za kubadilika.
Mfano: Kusimamia maelezo ya mtumiaji na kutuma arifa za barua pepe.
class UserManager {
public function createUser($userData) {
// Logic for creating a user
}
}
class EmailService {
public function sendEmail($emailData) {
// Logic for sending an email
}
}
Open/Closed Principle(OCP)
Kanuni hii inahimiza kupanua utendakazi kwa kuongeza msimbo mpya badala ya kurekebisha msimbo uliopo.
Mfano: Kushughulikia mbinu tofauti za malipo katika programu ya biashara ya mtandaoni.
interface PaymentProcessor {
public function processPayment();
}
class CreditCardPaymentProcessor implements PaymentProcessor {
public function processPayment() {
// Logic for processing credit card payment
}
}
class PayPalPaymentProcessor implements PaymentProcessor {
public function processPayment() {
// Logic for processing PayPal payment
}
}
Liskov Substitution Principle(LSP)
Kanuni hii inadai kuwa vipengee vya darasa linalotokana vinapaswa kubadilishwa kwa vitu vya darasa la msingi bila kuathiri usahihi wa programu.
Mfano: Kusimamia maumbo ya kijiometri.
abstract class Shape {
abstract public function area();
}
class Rectangle extends Shape {
public function area() {
return $this->width * $this->height;
}
}
class Square extends Shape {
public function area() {
return $this->side * $this->side;
}
}
Interface Segregation Principle(ISP)
Kanuni hii inashauri kuvunja miingiliano kuwa ndogo ili kuzuia kulazimisha madarasa kutekeleza njia ambazo hazihitaji.
Mfano: Violesura vya kusasisha na kuonyesha data.
interface UpdateableFeature {
public function updateFeature();
}
interface DisplayableFeature {
public function displayFeature();
}
Dependency Inversion Principle(DIP)
Kanuni hii inapendekeza kutumia sindano ya utegemezi kudhibiti utegemezi.
Mfano: Kutumia sindano ya utegemezi kudhibiti utegemezi.
class OrderProcessor {
private $dbConnection;
private $emailService;
public function __construct(DatabaseConnection $dbConnection, EmailService $emailService) {
$this->dbConnection = $dbConnection;
$this->emailService = $emailService;
}
}
Kumbuka kwamba kutumia SOLID kanuni katika PHP kunapaswa kufanywa kwa urahisi kulingana na madhumuni mahususi ya mradi wako na uelewa wako wa SOLID na PHP.