PHP Trait实战:5个高效代码复用技巧
1. 基础Trait使用
创建日志记录功能Trait:
trait Loggable {
protected function log($message) {
$logFile = 'app.log';
$timestamp = date('Y-m-d H:i:s');
file_put_contents($logFile, "[$timestamp] $messagen", FILE_APPEND);
}
}
class User {
use Loggable;
public function login() {
// 登录逻辑...
$this->log('用户登录: ' . $this->username);
}
}
// 使用
$user = new User();
$user->login();
2. 多Trait组合
组合多个Trait实现复杂功能:
trait Cacheable {
public function cache($key, $data, $ttl = 3600) {
// 缓存实现...
}
}
trait Validatable {
public function validate($data, $rules) {
// 验证逻辑...
}
}
class ProductService {
use Cacheable, Validatable;
public function getProduct($id) {
$key = "product_{$id}";
if ($cached = $this->getCache($key)) {
return $cached;
}
// 数据库查询...
}
}
3. Trait冲突解决
处理同名方法冲突:
trait A {
public function doSomething() {
echo '来自Trait A';
}
}
trait B {
public function doSomething() {
echo '来自Trait B';
}
}
class MyClass {
use A, B {
A::doSomething insteadof B; // 使用A的doSomething方法
B::doSomething as doSomethingB; // 将B的方法重命名
}
}
// 使用
$obj = new MyClass();
$obj->doSomething(); // 输出: 来自Trait A
$obj->doSomethingB(); // 输出: 来自Trait B
4. 抽象Trait方法
定义必须实现的抽象方法:
trait Discountable {
abstract public function getPrice();
public function applyDiscount($percent) {
$price = $this->getPrice();
return $price * (1 - $percent/100);
}
}
class Product {
use Discountable;
private $price;
public function getPrice() {
return $this->price;
}
}
复用方式 | 继承 | Trait |
---|---|---|
代码组织 | 垂直 | 水平 |
多重继承 | 不支持 | 支持 |
使用场景 | is-a关系 | has-a关系 |
5. 电商实战:订单状态Trait
实现订单状态管理:
trait OrderStatus {
private $status = 'pending';
public function getStatus() {
return $this->status;
}
public function markAsPaid() {
$this->status = 'paid';
$this->logStatusChange();
}
public function markAsShipped() {
$this->status = 'shipped';
$this->logStatusChange();
}
abstract protected function logStatusChange();
}
class Order {
use OrderStatus;
protected function logStatusChange() {
// 记录状态变更日志
$logger = new OrderLogger();
$logger->log($this->id, $this->status);
}
}
合理使用Trait可以大幅提高PHP代码的复用性和可维护性,特别适合在单继承语言中实现代码的水平复用。