Best practices to handle model events listening?

What are your best practices to handle model events listening?

  • in the model class itself?
  • in a init.php file
  • in the boot method of the plugin
  • something else?

Hi @chris!

I usually handle events in this way:

  1. Create file: %ModelName%ModelHandler.php (UserModelHandler.php for example)
    inside classes/event/user folder
  2. Fill it with some code:
    <?php namespace Acme\Plugin\Classes\Event\User;
    
    use RainLab\User\Models\User;
    
    /**
     * Class UserModelHandler
     * @package Acme\Plugin\Classes\Event\User
     */
    class UserModelHandler
    {
    
        /**
         * Add listeners
         * @param \October\Rain\Events\Dispatcher $event
         */
        public function subscribe($event)
        {
    		User::extend(function ($model) {
    			$this->extendAttributes($model);
    			$this->addRelations($model);
    			$this->addDynamicMethods($model);
    			// ...
    		});
        }
    
    	protected function extendAttributes(User $model)
    	{
    		// ...
    	}
    
    	protected function addRelations(User $model)
    	{
    		// ...
    	}
    
    	protected function addDynamicMethods(User $model)
    	{
    		// ...
    	}
    
    	// ...
    }
    
  3. Subscribe to Handler inside Plugin.php
    <?php namespace Acme\Plugin;
    
    use Backend, Event;
    use Acme\Plugin\Classes\Event\User\UserModelHandler;
    
    /**
     * Acme Plugin Information File
     */
    class Plugin extends PluginBase
    {
        // ...
    
        /**
         * Boot method, called right before the request route.
         *
         * @return void
         */
        public function boot()
        {
    		$this->addEventListeners();
        }
    
        protected function addEventListeners()
        {
            // User
            Event::subscribe(UserModelHandler::class);
            // ...
        }
    
        // ...
    }
    

Writing Event listeners in this way helps a lot if your app continues to grow from time to time, Plugin.php stays clean and plugin folder are organized and easy to navigate.

Example of project that has huge amount of listeners:

Plugin.php

Folder structure

Hope this helps!

1 Like

thanks @ReaZzon , that helps a lot to review my current way of doing it.
I like the structure of the approach that make things well organized and easy to be grasped by a new developer joining a project for example.

with this approach @ReaZzon , where do you put the model events handling such as “afterCreate”, “beforeValidate”, etc…?

Inside @ModelName@ModelHandler.php files

Example: