我正在尝试为RESTful API生成重写规则。我只想看看是否有比写出所有可能的重写组合更好的方法来完成这项工作。

好吧,所以我有4个查询变量要在URL中进行解释


指标
国家/地区
响应
调查

基本URL为www.example.com/some-page/ 4个变量的顺序将保持一致,但某些查询变量是可选的。

这样我就可以...

/indicator/{indicator value}/country/{country value}/response/{response value}/survey/{survey value}/


或...(无/ response /)
/indicator/{indicator value}/country/{country value}/survey/{survey value}/


或...

/indicator/{indicator value}/country/{country value}/


有比过滤rewrite_rules_array和添加我的重写规则数组更好的方法了手动创建的? Q4312079q rewrite_endpoint或add_rewrite_endpoint()对我有用吗?

#1 楼

我认为最好的选择是端点。您可以将所有数据作为一个简单的字符串来获取,因此可以决定如何解析它们,而不必担心与其他重写规则发生冲突。保持主要工作尽可能抽象,以数据不可知的方式修复WordPress API中的故障。

我将逻辑分为三个部分:控制器选择模型和视图,模型处理端点和一个或多个视图以返回一些有用的数据或错误消息。

控制器

让我们从控制器开始。它并没有太大的作用,因此我在这里使用了一个非常简单的函数:

add_action( 'plugins_loaded', 't5_cra_init' );

function t5_cra_init()
{
    require dirname( __FILE__ ) . '/class.T5_CRA_Model.php';

    $options = array (
        'callback' => array ( 'T5_CRA_View_Demo', '__construct' ),
        'name'     => 'api',
        'position' => EP_ROOT
    );
    new T5_CRA_Model( $options );
}


基本上,它会加载模型T5_CRA_Model并移交一些参数…和所有工作。控制器对模型或视图的内部逻辑一无所知。它只是粘在一起。这是您不能重复使用的唯一部分。这就是为什么我将其与其他部分分开。


现在,我们至少需要两个类:注册API的模型和用于创建输出的视图。

模型

此类将:


注册端点
捕获在没有任何其他参数的情况下调用端点的情况
填写由于第三方代码中的某些错误而丢失的重写规则
EP_ROOT修复带有静态首页和终结点的WordPress故障,将URI解析为一个数组(也可以将其分隔为一个数组) )
使用这些值调用回调处理程序

我希望代码能说明一切。 :)

模型对数据的内部结构或表示一无所知。因此,您可以使用它来注册数百个API,而无需更改一行。

<?php  # -*- coding: utf-8 -*-
/**
 * Register new REST API as endpoint.
 *
 * @author toscho http://toscho.de
 *
 */
class T5_CRA_Model
{
    protected $options;

    /**
     * Read options and register endpoint actions and filters.
     *
     * @wp-hook plugins_loaded
     * @param   array $options
     */
    public function __construct( Array $options )
    {
        $default_options = array (
            'callback' => array ( 'T5_CRA_View_Demo', '__construct' ),
            'name'     => 'api',
            'position' => EP_ROOT
        );

        $this->options = wp_parse_args( $options, $default_options );

        add_action( 'init', array ( $this, 'register_api' ), 1000 );

        // endpoints work on the front end only
        if ( is_admin() )
            return;

        add_filter( 'request', array ( $this, 'set_query_var' ) );
        // Hook in late to allow other plugins to operate earlier.
        add_action( 'template_redirect', array ( $this, 'render' ), 100 );
    }

    /**
     * Add endpoint and deal with other code flushing our rules away.
     *
     * @wp-hook init
     * @return void
     */
    public function register_api()
    {
        add_rewrite_endpoint(
            $this->options['name'],
            $this->options['position']
        );
        $this->fix_failed_registration(
            $this->options['name'],
            $this->options['position']
        );
    }

    /**
     * Fix rules flushed by other peoples code.
     *
     * @wp-hook init
     * @param string $name
     * @param int    $position
     */
    protected function fix_failed_registration( $name, $position )
    {
        global $wp_rewrite;

        if ( empty ( $wp_rewrite->endpoints ) )
            return flush_rewrite_rules( FALSE );

        foreach ( $wp_rewrite->endpoints as $endpoint )
            if ( $endpoint[0] === $position && $endpoint[1] === $name )
                return;

        flush_rewrite_rules( FALSE );
    }

    /**
     * Set the endpoint variable to TRUE.
     *
     * If the endpoint was called without further parameters it does not
     * evaluate to TRUE otherwise.
     *
     * @wp-hook request
     * @param   array $vars
     * @return  array
     */
    public function set_query_var( Array $vars )
    {
        if ( ! empty ( $vars[ $this->options['name'] ] ) )
            return $vars;

        // When a static page was set as front page, the WordPress endpoint API
        // does some strange things. Let's fix that.
        if ( isset ( $vars[ $this->options['name'] ] )
            or ( isset ( $vars['pagename'] ) and $this->options['name'] === $vars['pagename'] )
            or ( isset ( $vars['page'] ) and $this->options['name'] === $vars['name'] )
            )
        {
            // In some cases WP misinterprets the request as a page request and
            // returns a 404.
            $vars['page'] = $vars['pagename'] = $vars['name'] = FALSE;
            $vars[ $this->options['name'] ] = TRUE;
        }
        return $vars;
    }

    /**
     * Prepare API requests and hand them over to the callback.
     *
     * @wp-hook template_redirect
     * @return  void
     */
    public function render()
    {
        $api = get_query_var( $this->options['name'] );
        $api = trim( $api, '/' );

        if ( '' === $api )
            return;

        $parts  = explode( '/', $api );
        $type   = array_shift( $parts );
        $values = $this->get_api_values( join( '/', $parts ) );
        $callback = $this->options['callback'];

        if ( is_string( $callback ) )
        {
            call_user_func( $callback, $type, $values );
        }
        elseif ( is_array( $callback ) )
        {
            if ( '__construct' === $callback[1] )
                new $callback[0]( $type, $values );
            elseif ( is_callable( $callback ) )
                call_user_func( $callback, $type, $values );
        }
        else
        {
            trigger_error(
                'Cannot call your callback: ' . var_export( $callback, TRUE ),
                E_USER_ERROR
            );
        }

        // Important. WordPress will render the main page if we leave this out.
        exit;
    }

    /**
     * Parse request URI into associative array.
     *
     * @wp-hook template_redirect
     * @param   string $request
     * @return  array
     */
    protected function get_api_values( $request )
    {
        $keys    = $values = array();
        $count   = 0;
        $request = trim( $request, '/' );
        $tok     = strtok( $request, '/' );

        while ( $tok !== FALSE )
        {
            0 === $count++ % 2 ? $keys[] = $tok : $values[] = $tok;
            $tok = strtok( '/' );
        }

        // fix odd requests
        if ( count( $keys ) !== count( $values ) )
            $values[] = '';

        return array_combine( $keys, $values );
    }
}


视图

现在,我们必须对数据进行处理。对于不完整的请求,我们还可以捕获丢失的数据,或者将处理委托给其他视图或子控制器。这里是一个非常简单的示例:

br />重要的是:视图对端点一无所知。您可以使用它来处理完全不同的请求,例如wp-admin中的AJAX请求。您可以将视图拆分为自己的MVC模式,也可以仅使用简单的功能。

评论


数字。我喜欢这种类型的图案。

– kingkool68
13年3月22日在14:39