如何使用自定義事件和觀察者

第 1 步: 根據 frontendBackendYKM/Banner/etc/frontend/events.xml 中的要求建立 events.xml 檔案

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd">
    <event name="controller_action_predispatch">
        <observer name="ykm_banner_before" instance="YKM\Banner\Observer\Help" />
    </event>
</config>

第 2 步:

建立一個 Observer 檔案 YKM/Banner/Observer/Help.php

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Estdevs\Banner\Observer;

use Magento\Framework\Event\ObserverInterface;

class Help implements ObserverInterface
{
    
    public function execute(\Magento\Framework\Event\Observer $observer) {
       echo "this is good.";
    }
}