Php 钩子或事件以减少包之间的耦合
减少模块间耦合的最佳方法是什么 例如,如果我有一个Php 钩子或事件以减少包之间的耦合,php,laravel,events,module,hook,Php,Laravel,Events,Module,Hook,减少模块间耦合的最佳方法是什么 例如,如果我有一个发票包,并且它与客户包相关 我的理解是,我必须使用一个“钩子”系统,例如,在客户的编辑视图中插入一个带有客户发票列表的选项卡 反过来,使用事件系统从“发票”包的角度了解,例如,当有人试图删除客户机时 我想要实现的是减少耦合,这样如果我删除发票包,客户机包就不会受到影响 我怎样才能得到它?使用Laravel的事件系统?使用如下自定义类 我的职业: class HookRepository { /** * The repository items.
发票
包,并且它与客户
包相关
我的理解是,我必须使用一个“钩子”系统,例如,在客户的编辑视图中插入一个带有客户发票列表的选项卡
反过来,使用事件系统从“发票”包的角度了解,例如,当有人试图删除客户机时
我想要实现的是减少耦合,这样如果我删除发票包,客户机包就不会受到影响
我怎样才能得到它?使用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);
}
}
使用接口和抽象类实现SOLID的打开/关闭原则
但是对于接口,我无法插入视图。。。我想允许包之间的交互,但保持低耦合。我想我需要使用钩子和/或事件,但我不知道……。@Mr.Hook“但对于接口,我不能注入视图…”我不认为是这样,但我需要更详细的示例来确定。请记住,您定义了接口并决定了它们定义的内容。当我启用我的发票包时,我想在客户的“编辑”视图中插入一个带有客户发票的选项卡(我猜是带有钩子的)。然后,如果客户被删除,我想删除他们的所有发票。所以,我想我需要用于视图的钩子和用于删除的事件(以及其他操作,如向客户端添加新字段)