父類調用子類方法是**模板方法模式**的典型應用:父類定義算法骨架,延遲具體步驟到子類實現。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
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 父類調用子類方法本質是**多態動態分發**,關鍵在於:
$this->method() 調用工程上推薦:
abstract 強制子類實現關鍵方法final 鎖定模板方法防止被覆寫