In PHP framework development, code reuse is essential for improving development efficiency and maintainability. This article introduces several common object-oriented programming code reuse strategies, accompanied by practical examples.
Inheritance allows a child class to derive from a parent class, reusing the parent's methods and properties.
class ParentClass {
public function method() {
echo "Parent method";
}
}
class ChildClass extends ParentClass {
public function method() {
parent::method();
echo "Child method";
}
}
$child = new ChildClass();
$child->method(); // Output: "Parent methodChild method"Composition does not create a parent-child relationship but allows code reuse by including an instance of another class within a class.
class ClassWithMethod {
public function method() {
echo "ClassWithMethod";
}
}
class UsingClass {
private $methodClass;
public function __construct() {
$this->methodClass = new ClassWithMethod();
}
public function useMethod() {
$this->methodClass->method(); // Output: "ClassWithMethod"
}
}
$user = new UsingClass();
$user->useMethod();An interface defines a set of methods that other classes can implement, allowing code reuse and standardization.
interface MethodInterface {
public function method();
}
class ClassImplementingInterface implements MethodInterface {
public function method() {
echo "Method implemented";
}
}
$instance = new ClassImplementingInterface();
$instance->method(); // Output: "Method implemented"Traits, introduced in PHP 5.4, allow classes to reuse methods and properties without inheritance.
trait MethodTrait {
public function method() {
echo "Trait method";
}
}
class UsingTrait {
use MethodTrait;
}
$user = new UsingTrait();
$user->method(); // Output: "Trait method"Consider a form processing scenario with the following tasks:
We can reuse separate classes for these tasks using composition:
class FormProcessor {
private $validator;
private $dataSaver;
private $emailer;
public function __construct(ValidatorInterface $validator, DataSaverInterface $dataSaver, EmailerInterface $emailer) {
$this->validator = $validator;
$this->dataSaver = $dataSaver;
$this->emailer = $emailer;
}
public function process(array $data) {
if ($this->validator->validate($data)) {
$this->dataSaver->save($data);
$this->emailer->send("Form data saved");
}
}
}This class allows reusing code for form validation, data saving, and email sending, improving development efficiency and maintainability.