unorthodox use of apply_filters, is it OK to use it in the following way?

In case of complex projects, I thought about using apply_filters / add_filter in order to get an instance of a class accessible everywhere it is needed ( while avoiding using the instance in the global scope / creating multiple instances ).

here is an example:

namespace my_namespace;

add_action(‘init’, ‘my_namespaceset_user’, -1);

function set_user()
{
new User();
}

function get_user()
{
return apply_filters(‘get_defined_user’, null );
}

class User {

function __construct()
{
$this->set_up_everything();
add_filter(‘get_defined_user’, array( $this, ‘return_instance’ );
}

private function set_up_everything()
{
//some logic here, based on get_current_user_ID();
}

private function return_instance()
{
return $this;
}

public function do_sthg()
{
print ‘its working’;
}

//other methods
}

Then, anywhere i need to use the User methods for the current user.
I do this:

$user = my_namespaceget_user();
$user->do_sthg(); //-> ‘its working’

I must say i am not familiar with how apply_filters work in the background, so if anyone thinks it can cause troubles or this is not ideal, please let me know

Read more here:: unorthodox use of apply_filters, is it OK to use it in the following way?

Leave a Reply

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