正確移除 Behavior 不僅是解除引用,更涉及事件監聽器的清理與 owner 反向引用的斷開。本文詳細說明 detachBehavior()、detachBehaviors() 用法及底層 Behavior::detach() 實現機制。
// 移除特定命名行為
$component->detachBehavior('myBehavior1');
// 移除所有已綁定行為
$component->detachBehaviors();
兩個移除方法最終都會呼叫行為的 detach() 方法:
public function detach() {
// 僅當行為已綁定元件(有 owner)才需處理
if ($this->owner) {
// 1. 遍歷行為定義的事件,逐一解除綁定
foreach ($this->events() as $event => $handler) {
$this->owner->off($event, is_string($handler) ? [$this, $handler] : $handler);
}
// 2. 斷開 owner 反向引用
$this->owner = null;
}
}
Component::off() 移除先前在 attach() 階段掛載的所有事件處理器,防止記憶體洩漏與誤觸發$this->owner = null,切斷行為對元件的反向引用,讓 GC 能正常回收detachBehavior() 需行為名稱,匿名行為無法單獨移除detachBehaviors() 會遍歷所有行為呼叫 detach(),確保完整清理掌握正確移除機制,能確保專案中 Behavior 的動態掛載/卸載不會殘留副作用,是構建穩健可擴展系統的關鍵細節。