PHP code example of cmatosbc / wp-coderpress-endpoints
1. Go to this page and download the library: Download cmatosbc/wp-coderpress-endpoints library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
cmatosbc / wp-coderpress-endpoints example snippets
use CoderPress\Rest\{RestEndpointFacade, AbstractRestEndpoint};
use CoderPress\Cache\{RedisCache, MySqlCache, FileCache};
ve first arguments stand as they are for register_rest_route()
* but with callbacks now accepting \Closure functions instead.
*
* The middlewares arguments accepts an array of closures which will be
* sequentially executed and MUST have a $request parameter.
*
* The cache mechanism is automatically applied to the endpoint and accepts
* any PSR-16 compliant object. Optionally, the expire time and the type
* of serialization can be changed. Expires accepts any value in seconds as
* integer or a Datetime object (and then the time in seconds between that and
* the current time will be automatically extracted)
*
*/
namespace: 'testing/v1',
route: 'custom/',
args: [
'id' => [
'validate_callback' => function($param, $request, $key) {
return is_numeric($param);
}
],
],
callback: function (\WP_REST_Request $request) {
$postId = $request->get_param('id');
$postCategoryIds = wp_get_object_terms($postId, ['category'], ['fields' => 'ids']);
return get_posts([
'post_status' => 'publish',
'category__in' => $postCategoryIds,
'order' => 'relevance'
]);
},
permissionCallback: function () {
return is_user_logged_in();
},
/**
* Accepts any number of /Closure middleware functions - to each one of them,
* the $request object must be passed. For changes made to the WP_REST_Request object,
* the closure must return void(). However, the middleware can also return a response
* to the request easily by return a new WP_REST_Response object instead.
*/
middlewares: [
function (\WP_REST_Request $request) {
$request->set_param('id', 123);
},
function (\WP_REST_Request $request) {
if ($request->get_param('id') == 123) {
return new \WP_REST_Response(['message' => 'Invalid value'], 201);
}
}
],
/**
* Accepts any instance PSR-16 compliant (CacheInterface contract),
* this package comes with 3 usable examples (file, Redis and custom MySQL
* table caching drivers).
*/
cache: $cacheInstance,
/**
* Accepts 3 different serialize/unserialize methods - defaults to serialize(),
* but can be using JSON - AbstractRestEndpoint::SERIALIZE_JSON - or igbinary PHP
* extension which offers a more efficient serializing version
* - AbstractRestEndpoint::SERIALIZE_IGBINARY.
*/
cacheSerializingMethod: AbstractRestEndpoint::SERIALIZE_PHP,
/**
* Accepts seconds as integer value, but also DateTime objects - for the latter,
* the system will get the interval between NOW and the passed DateTime object time,
* so the cache will work as scheduled.
*/
cacheExpires: (new \DateTime())->modify('+1 day')
);
use CoderPress\Rest\RestEndpointFacade;
use CoderPress\Rest\Middleware\MiddlewareFactory;
// Create an endpoint with CORS support
RestEndpointFacade::createEndpoint(
namespace: 'api/v1',
route: 'posts',
callback: function($request) {
return ['data' => 'Your API response'];
},
permissionCallback: function() {
return true;
},
args: [],
methods: ['GET', 'POST', 'OPTIONS'],
middlewares: [
MiddlewareFactory::cors(
allowedOrigins: ['https://your-domain.com'],
allowedMethods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'X-Custom-Header'],
maxAge: 7200
)
]
);