add $request parameter to wordpress api callback like laravel

173 Views Asked by At

As you know you can create a new Request in laravel and pass it to controller methods, like so:

public function create(CreateNewBookRequest $request){
    //todo method logic
}

now I want to implement such a thing in wordpress REST API. As you know when we are registring a new route for wordpress REST API, we do this:

register_rest_route($this->namespace, $this->baseRoute . '/register', array(
    'methods'  => [WP_REST_Server::CREATABLE],
    'callback' => [$this, 'registerRouteCallback'],
));

and in registerRouteCallback method we have:

public function registerRouteCallback(WP_REST_Request $request)
{
    //todo method logic
}

Now how can I implement something like laravel $request in wordpress(specifaclly for validations). I want to use this approach in multiple places not just in REST API callback.

generally I'm looking for a way to have access to a class object inside a function without passing the object as a parameter, I want function to automatically create an object if it was not passed to it.

When I try to do this:

public function registerRouteCallback(RegisterRequest $request)
{
    //todo method logic
}

I'll get a fetal error:

Argument #1 ($request) must be of type RegisterRequest, WP_REST_Request given.
1

There are 1 best solutions below

0
janice macbeth On

try this function registerRouteCallback ($request) { }