首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

大型 PHP 專案開發指南:物件導向設計與進階技巧

     編輯:PHP 綜合知識

隨著專案規模增長,程式碼維護性與擴充性成為關鍵。本文系統介紹 PHP 物件導向程式設計(OOP)核心概念、進階技巧,並示範如何應用於大型專案架構。

PHP OOP 三大支柱

1. 封裝

透過類別隱藏內部實作細節,僅公開必要介面:

<?php
class User {
    private $id;
    private $email;
    private $passwordHash;

    public function __construct(string $email, string $password) {
        $this->email = $email;
        $this->passwordHash = password_hash($password, PASSWORD_BCRYPT);
    }

    public function verifyPassword(string $password): bool {
        return password_verify($password, $this->passwordHash);
    }

    // 僅提供必要的 getter,不提供 password setter
    public function getEmail(): string {
        return $this->email;
    }
}
?>

關鍵點:使用 `private`/`protected` 限制存取,避免外部直接操作內部狀態(如 `$user->password = '123'`)。PHP 7.1+ 支援型別宣告與回傳型別,強化契約。

2. 繼承

子類別繼承父類別特性,並可擴充或覆寫:

<?php
abstract class BaseModel {
    protected $pdo;
    protected $table;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }

    public function findById(int $id): ?array {
        $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }
}

class UserModel extends BaseModel {
    protected $table = 'users';

    public function findByEmail(string $email): ?array {
        $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE email = ?");
        $stmt->execute([$email]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }
}
?>

注意:PHP 不支援多重繼承,但可用 trait 實現程式碼複用。

3. 多型

同一介面,不同實作:

<?php
interface PaymentGateway {
    public function charge(float $amount, string $currency): bool;
}

class StripeGateway implements PaymentGateway {
    public function charge(float $amount, string $currency): bool {
        // Stripe API 呼叫
        return true;
    }
}

class PayPalGateway implements PaymentGateway {
    public function charge(float $amount, string $currency): bool {
        // PayPal API 呼叫
        return true;
    }
}

// 使用端不需知道具體實作
function processOrder(PaymentGateway $gateway, float $amount) {
    $gateway->charge($amount, 'TWD');
}
?>

進階技巧:序列化與物件持久化

PHP 原生 `serialize()` / `unserialize()` 僅保存屬性,不保存方法。現代專案建議:

  • 使用 JSON 格式儲存資料傳輸物件(DTO)。
  • 搭配 Doctrine、Eloquent 等 ORM 管理實體持久化。
  • 若需快取完整物件,考慮 igbinary 或 msgpack 擴充套件,效能優於原生序列化。

大型專案架構建議

  1. 領域驅動設計(DDD):將業務邏輯封裝在實體、值物件、領域服務中,控制器僅處理 HTTP 請求/回應。
  2. 依賴注入容器:使用 PHP-DI、Symfony DI 或 Laravel 容器管理類別依賴,降低耦合。
  3. Repository 模式:抽象資料存取層,方便單元測試與切換資料來源。
  4. 中介軟體管線:處理認證、日誌、CORS 等橫切關注點。
  5. 嚴格型別模式:檔案頂端宣告 `declare(strict_types=1);`,搭配 PHPStan/Psalm 靜態分析。

命名規範與程式碼風格

  • 類別名:`PascalCase`(如 `UserService`)
  • 方法/屬性:`camelCase`(如 `getUserById`)
  • 常數:`UPPER_SNAKE_CASE`(如 `MAX_LOGIN_ATTEMPTS`)
  • 介面:以 `Interface` 結尾或前綴 `I`(如 `LoggerInterface`)
  • 遵循 PSR-12 編碼風格規範。

掌握 OOP 核心概念並配合現代工具鏈(Composer、PHPUnit、PHPStan、CI/CD),才能駕馭大型 PHP 專案的複雜度,打造可維護、可測試、可擴充的高品質軟體。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved