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

by Jess_Pinkman   Last Updated August 14, 2019 10:08 AM

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_namespace\set_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_namespace\get_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



Related Questions


daily cost changing plugin

Updated September 30, 2018 14:08 PM

how to make wordpress remember my choice

Updated September 01, 2017 17:08 PM