Scoped Handler

In addition to the default hooks handler explained on the previous page, the Utilities Module comes pre-packaged with one more hooks handler -- the so-called ScopedHooksHandler.

The scoped handler inherits the DefaultHooksHandler so it still keeps a list of hooks arrays and registers them on run. However, the hooks registered have a so-called scope which is defined by a starting hook and an ending hook.

Basically this handler will automagically register all its hooks an a constructor-given hook and will unregister them on another constructor-given hook. This is useful for scenarios where you only want to enqueue some hooks during a specific method call, for example, and don't want them interfering with the rest of the request. Your custom filter for modifying SQL queries should really not bring the whole page down, but only your own custom output if something should go wrong.

You can use it like this:

<?php

use DeepWebSolutions\Framework\Utilities\Hooks\Handlers\ScopedHooksHandler;

class MyClass {
    public function output_my_content() {
        do_action( 'before-my-awesome-output' );
        
        // output ...
        
        do_action( 'after-my-awesome-output' );
    }
}

$scoped_handler = new ScopedHooksHandler( 
        'my-class-output-handler', 
        array( 'hook' => 'before-my-awesome-output' ), 
        array( 'hook' => 'after-my-awesome-output' )
    );
$scoped_handler ->add_filter( ... );
$scoped_handler ->remove_action( ... );

$my_class = new MyClass();
$my_class->output_my_content();

The scoped handler uses different semantics for the methods remove_filter and remove_action. Basically their purpose is to instruct the handler to temporarily unregister those hooks during the given scope.

If you want to unregister hooks that you've added to the handler using add_action and add_filter, please use the methods remove_added_filter and remove_added_action, respectively.

Of course, it's also possible to call the run and reset action methods manually by simply not setting the start and end hooks in the constructor:

<?php

$scoped_handler = new ScopedHooksHandler( 'my-class-output-handler' );
$scoped_handler ->add_filter( ... );
$scoped_handler ->remove_action( ... );

$my_class = new MyClass();

$scoped_handler->run();
$my_class->output_my_content();
$scoped_handler->reset();

Last updated