dartmoon/prestashop-hooks

将 PrestaShop Hooks 做成面向对象

v0.3.0 2023-08-21 09:46 UTC

This package is auto-updated.

Last update: 2024-09-21 15:59:02 UTC


README

PrestaShop hooks 正确实现!而不是在模块的主文件中污染所有的钩子定义,使用这个包,您可以将它们定义在自己的类中。

安装

  1. 安装包
composer require dartmoon/prestashop-hooks
  1. HasHookDispatcher 特性和 hooks 属性添加到模块的主类中
use Dartmoon\Hooks\Traits\HasHookDispatcher;

class YourModule
{
    use HasHookDispatcher;

    /**
     * Hook classes
     */
    protected $hooks = [
        //
    ];

    // ...
}
  1. 修复类构造函数,初始化钩子调度器
public function __construct()
{
    //...

    // Let's init the hook dispatcher
    $this->initHookDispatcher();
}
  1. 修复 install 方法以安装钩子
public function install()
{
    if (
        parent::install()
        && $this->registerHook($this->getHookDispatcher()->getAvailableHooks())
    ) {
        //...

        return true;
    }

    return false;
}

用法

创建钩子组类

让我们创建这个类。为了说明起见,假设我们在模块的 src/Hooks 文件夹中创建它们。

文件 src/Hooks/FrontAssetsHooks.php

<?php

namespace Dartmoon\MyModule\Hooks;

use Dartmoon\Hooks\AbstractHookGroup;

class FrontAssetsHooks extends AbstractHookGroup
{
    /**
     * Name of the hooks to register
     */
    protected $hooks = [
        'header',
        // You can register how many hooks you want
    ];

    public function header($params)
    {
        //...

        // $this->module is the instance of the module
        // $this->context is the instance of the current context
    }
}

注册钩子组类

将您的类放入模块主类的 hooks 属性中。

use Dartmoon\MyModule\Hooks\FrontAssetsHooks;

/**
 * Hook classes
 */
protected $hooks = [
    FrontAssetsHooks::class
];

重置模块

PrestaShop 只在安装时安装模块钩子,因此您需要重置模块。

许可证

本项目采用 MIT 许可证 - 有关详细信息,请参阅 LICENSE.md 文件。