PHP怎么提高代码复用

wen PHP项目 3

本文目录导读:

PHP怎么提高代码复用

  1. 面向对象编程(OOP)
  2. 设计模式
  3. 函数与工具类
  4. 依赖注入容器
  5. 服务层设计
  6. 事件驱动编程
  7. 使用Composer与代码包
  8. 模板方法模式
  9. 最佳实践建议
  10. 代码审查清单

在PHP中提高代码复用性是编写高质量、可维护代码的关键,以下是全面的策略,从基础到进阶:

面向对象编程(OOP)

继承(Inheritance)

abstract class Database {
    protected $connection;
    abstract public function connect();
    public function query($sql) {
        // 通用查询逻辑
    }
}
class MySQLDatabase extends Database {
    public function connect() {
        $this->connection = new PDO('mysql:...');
    }
}
class PostgreSQLDatabase extends Database {
    public function connect() {
        $this->connection = new PDO('pgsql:...');
    }
}

接口(Interface)

interface PaymentGateway {
    public function processPayment($amount);
    public function refund($transactionId);
}
class StripePayment implements PaymentGateway {
    public function processPayment($amount) {
        // Stripe 实现
    }
    public function refund($transactionId) {
        // Stripe 退款实现
    }
}

Traits(个性特征)

trait Loggable {
    public function log($message) {
        echo "[".date('Y-m-d H:i:s')."] $message\n";
    }
    public function emergencyLog($message) {
        $this->log("EMERGENCY: $message");
    }
}
class UserService {
    use Loggable;
    public function createUser($data) {
        $this->log("Creating new user");
        // 业务逻辑
    }
}

设计模式

单例模式

class DatabaseConnection {
    private static $instance = null;
    private $connection;
    private function __construct() {
        $this->connection = new PDO('mysql:...');
    }
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

工厂模式

interface Notifier {
    public function send($to, $message);
}
class EmailNotifier implements Notifier {
    public function send($to, $message) {
        // 发送邮件
    }
}
class SMSNotifier implements Notifier {
    public function send($to, $message) {
        // 发送短信
    }
}
class NotifierFactory {
    public static function create($type) {
        switch ($type) {
            case 'email':
                return new EmailNotifier();
            case 'sms':
                return new SMSNotifier();
            default:
                throw new Exception("Unknown notifier type");
        }
    }
}

组合模式

class Validator {
    private $rules = [];
    public function addRule(callable $rule) {
        $this->rules[] = $rule;
    }
    public function validate($data) {
        foreach ($this->rules as $rule) {
            if (!$rule($data)) {
                return false;
            }
        }
        return true;
    }
}

函数与工具类

通用工具函数

class StringHelper {
    public static function truncate($text, $length = 100) {
        if (strlen($text) <= $length) {
            return $text;
        }
        return substr($text, 0, $length - 3) . '...';
    }
    public static function slugify($text) {
        $text = strtolower($text);
        $text = preg_replace('/[^a-z0-9-]/', '-', $text);
        $text = preg_replace('/-+/', '-', $text);
        return trim($text, '-');
    }
}
class ArrayHelper {
    public static function flatten($array, $prefix = '') {
        $result = [];
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $result = array_merge($result, self::flatten($value, $prefix.$key.'.'));
            } else {
                $result[$prefix.$key] = $value;
            }
        }
        return $result;
    }
}

依赖注入容器

class Container {
    private $instances = [];
    private $definitions = [];
    public function set($key, $definition) {
        $this->definitions[$key] = $definition;
    }
    public function get($key) {
        if (!isset($this->instances[$key])) {
            $this->instances[$key] = $this->resolve($key);
        }
        return $this->instances[$key];
    }
    private function resolve($key) {
        $definition = $this->definitions[$key];
        if (is_callable($definition)) {
            return $definition($this);
        }
        return new $definition();
    }
}
// 使用
$container = new Container();
$container->set('database', function($c) {
    return new DatabaseConnection($c->get('config'));
});
$database = $container->get('database');

服务层设计

interface UserServiceInterface {
    public function createUser(array $data);
    public function updateUser($id, array $data);
    public function deleteUser($id);
}
class UserService implements UserServiceInterface {
    private $userRepository;
    private $validator;
    private $eventDispatcher;
    public function __construct(
        UserRepositoryInterface $userRepository,
        ValidatorInterface $validator,
        EventDispatcherInterface $eventDispatcher
    ) {
        $this->userRepository = $userRepository;
        $this->validator = $validator;
        $this->eventDispatcher = $eventDispatcher;
    }
    public function createUser(array $data) {
        if (!$this->validator->validate($data)) {
            throw new ValidationException('Invalid data');
        }
        $user = new User($data);
        $this->userRepository->save($user);
        $this->eventDispatcher->dispatch(new UserCreatedEvent($user));
        return $user;
    }
}

事件驱动编程

class EventDispatcher {
    private $listeners = [];
    public function addListener($event, callable $listener) {
        $this->listeners[$event][] = $listener;
    }
    public function dispatch($event, $data = null) {
        if (!isset($this->listeners[$event])) {
            return;
        }
        foreach ($this->listeners[$event] as $listener) {
            call_user_func($listener, $data);
        }
    }
}
// 业务逻辑
$dispatcher = new EventDispatcher();
$dispatcher->addListener('user.created', function($user) {
    // 发送欢迎邮件
});
$dispatcher->addListener('user.created', function($user) {
    // 记录日志
});

使用Composer与代码包

{
    "require": {
        "guzzlehttp/guzzle": "^7.0",
        "monolog/monolog": "^2.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/",
            "App\\Services\\": "src/services/"
        }
    }
}

模板方法模式

abstract class DataExporter {
    public function export($data) {
        $data = $this->prepareData($data);
        $formatted = $this->formatData($data);
        $this->saveData($formatted);
    }
    protected function prepareData($data) {
        // 通用数据处理
        return $data;
    }
    abstract protected function formatData($data);
    abstract protected function saveData($data);
}
class CSVExporter extends DataExporter {
    protected function formatData($data) {
        // CSV 格式化
    }
    protected function saveData($data) {
        // 保存CSV文件
    }
}

最佳实践建议

分层架构

- Controller (控制器层)
  - Request -> Validate -> Call Service -> Response
- Service (服务层)
  - 业务逻辑,事务管理
- Repository (数据访问层)
  - 数据库操作,查询封装
- Model (模型层)
  - 数据结构,业务规则

使用静态工具

class DateHelper {
    public static function getAge($birthdate) {
        $birth = new DateTime($birthdate);
        $now = new DateTime();
        return $birth->diff($now)->y;
    }
}

参数配置化

class EmailService {
    private $config;
    public function __construct(array $config) {
        $this->config = $config;
    }
    public function send($to, $subject, $body) {
        // 使用 $this->config['smtp_host'] 等
    }
}
// 配置文件
$config = [
    'smtp_host' => 'smtp.example.com',
    'smtp_port' => 587,
    'smtp_user' => 'user',
    'smtp_pass' => 'pass'
];

代码审查清单

  • ✅ 避免代码重复(DRY原则)
  • ✅ 单一职责原则(SRP)
  • ✅ 开闭原则(OCP)
  • ✅ 使用接口而非具体类
  • ✅ 充分利用Composer包
  • ✅ 合理使用 Traits
  • ✅ 设计模式的应用
  • ✅ 参数化配置
  • ✅ 编写单元测试
  • ✅ 使用代码生成模板

通过运用这些策略,可以显著提高PHP代码的复用性,降低维护成本,并提升开发效率,最好的代码复用是模块化、解耦和通用性的综合体现。

抱歉,评论功能暂时关闭!