Single Responsibility Principle(SRP)
Prinsip iki nyatakake yen saben kelas kudu nduweni tanggung jawab siji. Iku nandheske sing kelas kudu nindakake siji fungsi tartamtu lan ora duwe kakehan alasan kanggo ngganti.
Conto: Ngatur informasi pangguna lan ngirim kabar email.
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)
Prinsip iki nyengkuyung nambah fungsi kanthi nambah kode anyar tinimbang ngowahi kode sing wis ana.
Conto: Nangani macem-macem cara pembayaran ing aplikasi e-commerce.
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)
Prinsip iki negesake manawa obyek saka kelas asale kudu bisa diganti kanggo obyek kelas dasar tanpa mengaruhi akurasi program kasebut.
Tuladha: Ngatur wangun geometris.
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)
Prinsip iki menehi saran supaya antarmuka rusak dadi luwih cilik supaya ora meksa kelas kanggo ngetrapake metode sing ora dibutuhake.
Conto: Antarmuka kanggo nganyari lan nampilake data.
interface UpdateableFeature {
public function updateFeature();
}
interface DisplayableFeature {
public function displayFeature();
}
Dependency Inversion Principle(DIP)
Prinsip iki nyaranake nggunakake injeksi dependensi kanggo ngatur dependensi.
Conto: Nggunakake injeksi dependensi kanggo ngatur dependensi.
class OrderProcessor {
private $dbConnection;
private $emailService;
public function __construct(DatabaseConnection $dbConnection, EmailService $emailService) {
$this->dbConnection = $dbConnection;
$this->emailService = $emailService;
}
}
Elinga yen ngetrapake SOLID prinsip ing PHP kudu ditindakake kanthi fleksibel adhedhasar tujuan spesifik proyek sampeyan lan pemahaman sampeyan SOLID lan PHP.