亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用于減少包之間耦合的掛鉤或事件

用于減少包之間耦合的掛鉤或事件

PHP
鳳凰求蠱 2024-01-19 15:44:57
減少模塊之間耦合的最佳方法是什么?例如,如果我有一個Invoice包并且它與該包相關Customer。我的理解是,我必須使用“掛鉤”系統來注入,例如,在客戶的編輯視圖中插入一個包含客戶發票列表的選項卡。反過來,從“Invoice”包的角度,使用事件系統來了解,例如,何時有人試圖刪除客戶端。我想要實現的是減少耦合,這樣如果我刪除發票包,客戶端包不受影響。我怎么才能得到它?使用 Laravel 的事件系統?使用如下所示的自定義類?我的鉤子類:class HookRepository{/** * The repository items. * * @var \Illuminate\Support\Collection */protected $items;/** * Create a new repository instance. * * @return void */public function __construct(){    $this->items = collect();}/** * Dynamically call methods. * * @param  string  $method * @param  array  $arguments * @return mixed */public function __call(string $method, array $arguments){    return $this->items->{$method}(...$arguments);}/** * Register a new hook callback. * * @param  string|array  $hook * @param  callable  $callback * @param  int  $priority * @return void */public function register($hook, callable $callback, int $priority = 10): void{    $this->items->push(compact('hook', 'callback', 'priority'));}/** * Apply the callbacks on the given hook and value. * * @param  string  $hook * @param  array  $arguments * @return mixed */public function apply(string $hook, ...$arguments){    return $this->items->filter(function ($filter) use ($hook) {        return !! array_filter((array) $filter['hook'], function ($item) use ($hook) {            return Str::is($item, $hook);        });    })->sortBy('priority')->reduce(function ($value, $filter) use ($arguments) {        return call_user_func_array($filter['callback'], [$value] + $arguments);    }, $arguments[0] ?? null);}}
查看完整描述

1 回答

?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

使用接口和抽象類來實現S O LID的開閉原則

  1. 識別一個接口。ClassA想從ClassB得到什么

  2. 概括 - 當您擁有一個接口時,您將能夠識別大多數需要實現它的類將需要的常見操作。(不要在這里嘗試過多的面向未來,否則很可能會適得其反)

注意:如果您這樣做是希望避免重構代碼。忘了它。:) 這只會使事情變得更加容易,這已經是一個巨大的好處。

避免使用鉤子來實現結構和/或行為模式。

編輯> Package 和 Hook 都不是 Laravel 或設計模式術語的一部分。

這本身應該給你一個提示。

讓我來玩一個猜謎游戲:

    <?php

    PackageInterface {

        public function enable();

        public function disable();

        public function isEnabled();

        public function getHooks(): HookInterface[];

    }

    HookInterface {

        public function injectView();

        // or maybe

        public function injectIntoView($view);

    }


這完全取決于您何時加載包并將某些內容注入視圖中。


例如,您可以在客戶自己啟用該包時使用該enable()包$invoice->wasPaid()$customer->enable($package)


查看完整回答
反對 回復 2024-01-19
  • 1 回答
  • 0 關注
  • 125 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號