There is no problem not worth solving, and no technology not worth learning!

In Laravel 6, refactoring based on event subscribers

1. The current implementation is as follows, register events and listeners in the Listen property of the EventServiceProvider. /App/Providers/EventServiceProvider.php


use Illuminate\Cache\Events\CacheHit;
use Illuminate\Cache\Events\CacheMissed;
use Illuminate\Cache\Events\KeyForgotten;
use Illuminate\Cache\Events\KeyWritten;
use App\Listeners\Cache\LogCacheHitListener;
use App\Listeners\Cache\LogCacheMissedListener;
use App\Listeners\Cache\LogKeyForgottenListener;
use App\Listeners\Cache\LogKeyWrittenListener;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        CacheHit::class => [
            LogCacheHitListener::class
        ],

        CacheMissed::class => [
            LogCacheMissedListener::class
        ],

        KeyForgotten::class => [
            LogKeyForgottenListener::class,
        ],

        KeyWritten::class => [
            LogKeyWrittenListener::class,
        ],
    ];


2. One of the listeners: LogKeyWrittenListener is implemented as follows, /app/Listeners/Cache/LogKeyWrittenListener.php


key, ThemePreviewInterface::THEME_EDITOR_SESSION_PREFIX) !== false) {
            Log::debug('theme_editor_session_key_written', [
                'key' => $event->key,
                'tags' => $event->tags,
                'value' => $event->value,
                'seconds' => $event->seconds
            ]);
        }
    }
}



3. One of the listeners: LogCacheHitListener is implemented as follows, /app/listeners/cache/logCacheHitListener.php


key, ThemePreviewInterface::THEME_EDITOR_SESSION_PREFIX) !== false) {
            Log::debug('theme_editor_session_cache_hit', [
                'key' => $event->key,
                'tags' => $event->tags,
                'value' => $event->value
            ]);
        }
    }
}



4. Decide to refactor based on event subscribers. Write the event subscriber CacheEventSubscriber to merge 4 listener files into 1.


isThemeEditorSessionLogDebug($event)) {
            Log::debug('theme_editor_session_cache_hit', [
                'key' => $event->key,
                'tags' => $event->tags,
                'value' => $event->value
            ]);
        }
    }

    /**
     * 处理缓存未命中事件
     */
    public function handleLogCacheMissed($event)
    {
        if ($this->isThemeEditorSessionLogDebug($event)) {
            Log::debug('theme_editor_session_cache_missed', [
                'key' => $event->key,
                'tags' => $event->tags
            ]);
        }
    }

    /**
     * 处理缓存删除事件
     */
    public function handleLogKeyForgotten($event)
    {
        if ($this->isThemeEditorSessionLogDebug($event)) {
            Log::debug('theme_editor_session_key_forgotten', [
                'key' => $event->key,
                'tags' => $event->tags
            ]);
        }
    }

    /**
     * 处理缓存写入事件
     */
    public function handleLogKeyWritten($event)
    {
        if ($this->isThemeEditorSessionLogDebug($event)) {
            Log::debug('theme_editor_session_key_written', [
                'key' => $event->key,
                'tags' => $event->tags,
                'value' => $event->value,
                'seconds' => $event->seconds
            ]);
        }
    }

    /**
     * 是否记录主题编辑器 Session 日志
     * @return bool
     */
    private function isThemeEditorSessionLogDebug($event)
    {
        return config('app.debug') === true && strpos($event->key, ThemePreviewInterface::THEME_EDITOR_SESSION_PREFIX) !== false;
    }

    /**
     * 为订阅者注册监听器
     *
     * @param  Dispatcher  $events
     */
    public function subscribe($events)
    {
        $events->listen(
            CacheHit::class,
            'App\Listeners\CacheEventSubscriber@handleLogCacheHit'
        );

        $events->listen(
            CacheMissed::class,
            'App\Listeners\CacheEventSubscriber@handleLogCacheMissed'
        );

        $events->listen(
            KeyForgotten::class,
            'App\Listeners\CacheEventSubscriber@handleLogKeyForgotten'
        );

        $events->listen(
            KeyWritten::class,
            'App\Listeners\CacheEventSubscriber@handleLogKeyWritten'
        );
    }
}



5. Delete events and listeners in the Listen property of the EventServiceProvider, and then add a subscriber to the Subscribe property


class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
    ];

    protected $subscribe = [
        \App\Listeners\CacheEventSubscriber::class
    ];



6. After testing, there are 4 events, of which the keyforgotten is not triggered when the cache data is used to delete the cached data. When cached data is removed from the cache using the forget method, the keyforgotten is triggered.


Cache::put(ThemePreviewInterface::THEME_EDITOR_SESSION_PREFIX . '20220921', '20220921.value', ThemePreviewInterface::TTL);
Cache::forget(ThemePreviewInterface::THEME_EDITOR_SESSION_PREFIX . '20220921');



[2022-09-21 10:11:12] local.DEBUG: theme_editor_session_key_written {
    "key": "theme_editor_session:20220921",
    "tags": [],
    "value": "20220921.value",
    "seconds": 86400
} 
[2022-09-21 10:14:19] local.DEBUG: theme_editor_session_key_forgotten {
    "key": "theme_editor_session:20220921",
    "tags": []
} 


PHP / Laravel / Yii2 Legacy Project Maintenance & Long-Term Technical Support

If your PHP / Laravel / Yii2 project is already in production but needs bug fixing, API troubleshooting, performance optimization, developer handover support, or long-term maintenance, feel free to contact me for remote technical support.

Ideal For:
✅ PHP legacy systems without active maintenance
✅ Laravel / Yii2 project bug fixes
✅ Admin panel feature iterations
✅ RESTful API troubleshooting
✅ MySQL / Redis / Nginx performance issues
✅ Long-term remote part-time maintenance

We can start with a small task:
✅ Production error troubleshooting
✅ API issue analysis
✅ Slow query and performance bottleneck diagnosis
✅ Initial code structure review
✅ Deployment environment and log inspection

If you would like to discuss your project, please contact me and mention: PHP Maintenance Consultation.

Contact Me:
Telegram: @shuijingwan
WeChat: 13980074657
Email: shuijingwanwq@gmail.com

评论

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.