Make WordPress Core


Ignore:
Timestamp:
09/23/2019 08:24:59 PM (5 years ago)
Author:
kadamwhite
Message:

REST API: Introduce WP_Post_Type::get_rest_controller() caching method to prevent unnecessary REST controller construction.

Cache REST controller references on their associated post type object to prevent unnecessary controller re-instantiation, which previously caused "rest_prepare_{$post_type}" and "rest_{$post_type}_query" to run twice per request.

Props TimothyBlynJacobs, patrelentlesstechnologycom.
Fixes #45677.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/class-wp-post-type.php

    r46160 r46272  
    335335     */
    336336    public $rest_controller_class;
     337
     338    /**
     339     * The controller instance for this post type's REST API endpoints.
     340     *
     341     * Lazily computed. Should be accessed using {@see WP_Post_Type::get_rest_controller()}.
     342     *
     343     * @since 5.3.0
     344     * @var WP_REST_Controller $rest_controller
     345     */
     346    private $rest_controller;
    337347
    338348    /**
     
    683693        remove_action( 'future_' . $this->name, '_future_post_hook', 5 );
    684694    }
     695
     696    /**
     697     * Gets the REST API controller for this post type.
     698     *
     699     * Will only instantiate the controller class once per request.
     700     *
     701     * @since 5.3.0
     702     *
     703     * @return WP_REST_Controller|null The controller instance, or null if the post type
     704     *                                 is set not to show in rest.
     705     */
     706    public function get_rest_controller() {
     707        if ( ! $this->show_in_rest ) {
     708            return null;
     709        }
     710
     711        $class = $this->rest_controller_class ? $this->rest_controller_class : WP_REST_Posts_Controller::class;
     712
     713        if ( ! class_exists( $class ) ) {
     714            return null;
     715        }
     716
     717        if ( ! is_subclass_of( $class, WP_REST_Controller::class ) ) {
     718            return null;
     719        }
     720
     721        if ( ! $this->rest_controller ) {
     722            $this->rest_controller = new $class( $this->name );
     723        }
     724
     725        return $this->rest_controller;
     726    }
    685727}
Note: See TracChangeset for help on using the changeset viewer.