There’s several things wrong here, none really related to OOP.
Firstly, you seem to be attempting to register the REST routes on plugin activation. This is incorrect. Routes need to be registered for every request, so BusinessCustomersApiController->register_routes()
needs to run on every request. You do this by hooking that function to the rest_api_init
.
The problem there is that your use of add_action()
to add that hook is inside the callback. Since register_routes()
needs to be hooked to run, but the hooking happens inside register_routes()
, the function will never run.
So, there’s two things you need to do to fix this:
- Move the call to
add_action()
into a separate method. - Run that method on every request.
Here’s how I’d do it:
- Remove any activation or deactivation related methods. You’re not using them.
- Add a new method (I’ll call it
init()
) to the classes, and put any use ofadd_action()
into those. - Call the that method on the class instance after creating it.
The result will be something like this. Note that I’ve removed code that wasn’t relevant to the issue, to demonstrate the solution:
class BusinessCustomersPlugin {
function init(){
$_apiController = new BusinessCustomersApiController();
$_apiController->init();
}
}
$businessCustomers = new BusinessCustomersPlugin();
$businessCustomers->init();
class BusinessCustomersApiController {
public function __construct() {
$this->namespace="/customers/org/v1/";
}
public function init() {
add_action( 'rest_api_init', [ $this, 'register_routes' ] );
}
public function register_routes() {
register_rest_route(
$this->namespace,
'test/',
[
'methods' => 'GET',
'callback' => [ $this, 'test' ],
]
);
}
public function test() {
return 'test';
}
}