В настоящее время я разрабатываю свой первый плагин для Wordpress, и я столкнулся с проблемой REST API, которую я не совсем понимаю. Может быть, есть лучший подход, чем мой, о котором я еще не знаю, поэтому я рад любой помощи, которая есть там!
Вот сделка:
Я создаю API, который должен обслуживать кэшированные данные из Wordpress mysql db. Я сохраняю данные (URL, MIME-тип, [...]) из веб-ресурсов в базу данных, которую затем хочу обслуживать. Кэшируемые ресурсы определены в файле политики, который выглядит примерно так:
policy. json
{
"files":
[
{
"resource_url": "https://example.come/assets/images/image.png",
(...)
},
(...)
]
}
Поскольку количество файлов динамическое. c мой сервис должен приспособиться к любым настраиваемым маршрутам, диктуемым файлом политики. Например, в приведенном выше случае предполагается, что ресурс будет обслуживаться через мой сайт Wordpress, который изначально был создан с example.com. Поэтому, если запрошено https://my-wordpress-site.com/wp-json/example/v1/assets/images/image.png
, предполагается, что кэшированный файл из https://example.come/assets/images/image.png
будет обслуживаться.
Мой REST API выглядит примерно так:
mypl / rest_api. php
<?php
function custom_resource_endpoint() {
return new WP_REST_Response("The requested resource could not be found.", 400);
}
function rpc_through_endpoint( $request_data ) {
$route = $request_data->get_route();
$header = $request_data->get_headers();
$data = $request_data->get_body();
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://example.com" . str_replace('example/v1/', '', $route));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/octet-stream'));
41 $response = curl_exec($curl);
curl_close($curl);
return new WP_REST_Response($response, 200);
}
function register_custom_routes() {
$rest_prefix = 'example/v1';
register_rest_route($rest_prefix, '/rpc', array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'rpc_through_endpoint'
));
register_rest_route($rest_prefix, '(/w)', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'custom_resource_endpoint'
));
}
add_action('rest_api_init', 'register_custom_routes');
// Interceptor.
function serve_static_resources($served, $result, $request, $server) {
$route = $request->get_route();
if (ends_with($route, 'rpc')) {
$served = false;
} else {
$file_uri = str_replace('/example/v1/', 'https://example/', $route);
if ($file_uri != null) {
$resource = checkLatestResourceByUri($file_uri);
if(count($resource) > 0) {
$vars=get_object_vars($resource[0]);
http_response_code(200);
header( 'Content-Type: ' . $vars['resource_mime_type'], true );
92 echo $vars['resource_data'];
$served = true;
}
}
}
return $served;
}
add_filter('rest_pre_serve_request', 'serve_static_resources', 10, 4);
Как я думал об этом, я создаю READABLE (GET) rest route, который принимает все запросы к остальному API. Как только запрос поступает, он перехватывается фильтром rest_pre_serve_request
, чтобы проверить базу данных, кэширован ли запрошенный файл, и, если да, обслужить его. Вот мой подход к этому:
Согласно документации, я могу просто вывести данные из фильтра и вернуть true
или false
, чтобы указать, был ли запрос уже обработан или нет. Однако в моем случае мне также нужно добавить дополнительные данные, такие как Status-Code
и Content-Type
, для ответа, чтобы клиенты могли правильно его обработать. Теперь вот суть. Лог c работает точно так, как я хочу, и обслуживает запросы, как и должно быть, но все же я уже получаю заголовки classi c отправлены предупреждения от PHP, которые выглядят так:
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 596
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 597
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 596
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 596
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 598
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 597
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 597
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 599
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 598
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 598
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 599
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 599
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:41) in /var/www/html/wp-includes/rest-api/class-wp-rest-server.php on line 1337
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:41) in /var/www/html/wp-includes/rest-api.php on line 596
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:41) in /var/www/html/wp-includes/rest-api.php on line 597
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:41) in /var/www/html/wp-includes/rest-api.php on line 598
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:41) in /var/www/html/wp-includes/rest-api.php on line 599
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 596
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 596
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 596
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 597
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 597
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 597
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 598
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 598
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 598
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 599
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 599
[06-Aug-2020 10:47:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/plugins/mypl/rest_api.php:92) in /var/www/html/wp-includes/rest-api.php on line 599
Строки 41 и 92 отмечены в приведенном выше коде.
Итак, есть ли что-нибудь, что Я здесь делаю в корне неправильно ?? Или, может быть, кто-то знает, как правильно обращаться с этим консервированным материалом?
Я ценю вашу помощь !!