Making a class available via actions filters

Build some kind of a registry where other plugins can register new tabs. Let’s say your plugin’s admin page handler is called Main_Controller:

class Main_Controller {

    protected $tabs;

    public function __construct()
    {
        $this->tabs = new Tab_List;

        do_action( 'register_tabs', $this->tabs );
    }

    public function create_tabs() {
        $all_tabs = $this->tabs->get_tabs();

        if ( empty ( $all_tabs ) )
            return;

        foreach ( $all_tabs as $id => $tab ) {
            // print the tab
        }
    }
}

Tab_List is the list with all registered tabs:

class Tab_List {

    protected $tabs = array();

    public function register( $id, Tab $tab ) {
        $this->tabs[ $id ] = $tab;
    }

    public function get_tabs() {
        return $this->tabs;
    }
}

The method register expects a well defined instance of a class Tab:

class Tab {

    // Have to be replaced.
    protected $properties = array(
        'tab_title'        => 'MISSING TAB TITLE',
        'page_title'       => 'MISSING PAGE TITLE',
        'content_callback' => '__return_false',
        'save_callback'    => '__return_false'
    );

    public function __set( $name, $value ) {
        if ( isset ( $this->properties[ $name ] ) )
            $this->properties[ $name ] = $value;
    }

    public function __get( $name ) {
        if ( isset ( $this->properties[ $name ] ) )
            return $this->properties[ $name ];
    }
}

Now other plugins can register their tabs with a simple hook:

add_action( 'register_tabs', function( Tab_List $tab_list )
{
    $data = new My_Color_Data;
    $view = new My_Color_View( $data );

    $my_tab = new Tab;
    $my_tab->tab_title="Colors";
    $my_tab->page_title="Set custom colors";
    $my_tab->content_callback = array( $view, 'print_tab' );
    $my_tab->save_callback    = array( $data, 'save_tab' );

    $tab_list->register( 'colors', $my_tab );
});

The classes My_Color_Data and My_Color_View are custom. I leave that up to your imagination. 🙂

See also:

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)