萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 父類調用子類方法:模板方法模式實戰與原理解析

核心概念

父類調用子類方法是**模板方法模式**的典型應用:父類定義算法骨架,延遲具體步驟到子類實現。PHP 支持通過 $this->method() 實現多態調用,前提是**實例化的是子類對象**。

基礎示例

<?php
/**
 * 基礎應用類:定義執行流程模板
 */
abstract class BaseApp
{
    /** 模板方法:定義算法骨架 */
    final public function run(): void
    {
        $this->initialize();
        $action = $this->resolveAction();
        $this->executeAction($action);
        $this->finalize();
    }

    /** 鉤子方法:子類可選覆寫 */
    protected function initialize(): void {}
    protected function finalize(): void {}

    /** 抽象方法:子類必須實現 */
    abstract protected function resolveAction(): string;
    abstract protected function executeAction(string $action): void;
}

/**
 * 具體應用:默認首頁
 */
class DefaultApp extends BaseApp
{
    protected function resolveAction(): string
    {
        return 'index';
    }

    protected function executeAction(string $action): void
    {
        // 動態調用子類方法:indexAction, listAction 等
        $method = $action . 'Action';
        if (method_exists($this, $method)) {
            $this->$method();
        } else {
            throw new BadMethodCallException("Action '$method' 不存在");
        }
    }

    protected function indexAction(): void
    {
        echo "DefaultApp->indexAction() invoked\n";
    }
    
    protected function listAction(): void
    {
        echo "列表頁邏輯\n";
    }
}

/** 入口腳本 */
$app = new DefaultApp();
$app->run(); // 輸出: DefaultApp->indexAction() invoked

進階:控制器基類 (MVC 框架核心)

abstract class Controller
{
    protected Request $request;
    protected Response $response;

    public function __construct(Request $request, Response $response)
    {
        $this->request = $request;
        $this->response = $response;
    }

    /** 分發入口:路由解析 -> 調用 Action */
    final public function dispatch(string $action): void
    {
        // 前置過濾器
        if (!$this->beforeAction($action)) {
            return; // 如權限失敗已在 beforeAction 中輸出響應
        }

        $method = $action . 'Action';
        if (!method_exists($this, $method)) {
            $this->notFound();
            return;
        }

        // 調用子類具體 Action 方法
        $this->$method();

        // 後置過濾器
        $this->afterAction($action);
    }

    // 鉤子方法 (可選覆寫)
    protected function beforeAction(string $action): bool { return true; }
    protected function afterAction(string $action): void {}
    protected function notFound(): void { $this->response->setStatusCode(404)->send('Not Found'); }
}

// 子類控制器
class UserController extends Controller
{
    protected function beforeAction(string $action): bool
    {
        // 除 login/reg 外需登錄
        if (!in_array($action, ['login', 'register']) && !$this->isLoggedIn()) {
            $this->response->redirect('/login');
            return false;
        }
        return true;
    }

    protected function loginAction(): void
    {
        // 登錄邏輯
        $this->response->json(['token' => 'abc123']);
    }

    protected function profileAction(): void
    {
        $this->response->json(['user' => $this->currentUser()]);
    }
}

原理解析:為什麼能調用子類方法?

class ParentClass {
    public function callChild() {
        $this->childMethod(); // 動態分發
    }
}

class ChildClass extends ParentClass {
    public function childMethod() {
        echo "Child method\n";
    }
}

$obj = new ChildClass();
$obj->callChild(); // 輸出: Child method

// 關鍵點:
// 1. $obj 是 ChildClass 實例
// 2. $this 在 ParentClass::callChild() 中綁定到 $obj (ChildClass 實例)
// 3. PHP 方法調用基於實際對象類型動態分發 (多態)
// 4. 如果 new ParentClass() 再 callChild() -> Fatal Error: 未定義方法

常見誤區與最佳實踐

❌ 錯誤:父類實例化嘗試調用子類方法

$parent = new BaseApp(); // 抽象類不可實例化,假設非抽象
$parent->run(); // Fatal: 未定義 resolveAction()

✅ 正確:依賴倒置,面向接口編程

interface AppInterface {
    public function run(): void;
}

class Application implements AppInterface {
    // 組合而非繼承
    private ControllerResolver $resolver;
    
    public function run(): void {
        $controller = $this->resolver->resolve($this->request);
        $controller->dispatch($this->request->getAction());
    }
}

設計模式對比

模式父類角色子類角色適用場景
模板方法定義算法骨架 (final)實現具體步驟 (abstract/hook)流程固定、步驟可變
策略模式委託策略對象實現策略接口算法族可互換、運行時切換
工廠方法聲明工廠方法實現創建邏輯對象創建邏輯複雜/可變

實戰:插件系統鉤子機制

class PluginManager
{
    private array $hooks = [];

    /** 註冊鉤子:$hookName => [callback, priority] */
    public function addHook(string $hookName, callable $callback, int $priority = 10): void
    {
        $this->hooks[$hookName][] = [$callback, $priority];
        // 按優先級排序
        usort($this->hooks[$hookName], fn($a, $b) => $a[1] <=> $b[1]);
    }

    /** 執行鉤子:父類流程中調用 */
    public function doHook(string $hookName, mixed &$data = null): void
    {
        if (empty($this->hooks[$hookName])) return;
        
        foreach ($this->hooks[$hookName] as [$callback, $priority]) {
            // 子類/插件通過 callback 參與流程
            $callback($data, $this);
        }
    }
}

// 基礎服務類
class BaseService
{
    protected PluginManager $plugins;
    
    public function __construct(PluginManager $plugins)
    {
        $this->plugins = $plugins;
    }
    
    public function process(Data $data): Result
    {
        $this->plugins->doHook('before_process', $data);
        
        $result = $this->doProcess($data); // 子類實現核心邏輯
        
        $this->plugins->doHook('after_process', $result);
        return $result;
    }
    
    abstract protected function doProcess(Data $data): Result;
}

總結

PHP 父類調用子類方法本質是**多態動態分發**,關鍵在於:

  1. 實例化的是**子類對象**
  2. 父類方法中通過 $this->method() 調用
  3. 子類**覆寫**或**實現抽象方法**

工程上推薦:

  • 用 abstract 強制子類實現關鍵方法
  • 用 final 鎖定模板方法防止被覆寫
  • 鉤子方法提供可選擴展點
  • 複雜場景考慮**組合 > 繼承** (策略模式、事件驅動)
copyright © 萬盛學電腦網 all rights reserved