Skip to Content

About WpMVC Routing

WpMVC Routing is a powerful routing system for WordPress plugins that is similar to the popular PHP framework Laravel. This package makes use of the WordPress REST route system and includes its own custom route system, known as the Ajax Route.

One of the key features of WpMVC Routing is its support for middleware. Middleware allows you to perform additional actions before each request.

By using WpMVC Routing in your WordPress plugin, you can easily create custom routes and middleware to handle a wide variety of requests, including AJAX requests, with ease. This makes it an excellent tool for developing modern and dynamic WordPress plugins that require advanced routing capabilities and additional security measures.

Requirement

WpMVC routing requires a dependency injection (DI) container. We do not use any hard-coded library, so you can choose to use any DI library you prefer. However, it is important to follow our DI structure, which includes having the set and get methods in your DI container.

We recommend using symfony/dependency-injection  as it already has these methods implemented in the package.

Methods structure

Here is the structure of the methods that your DI container should have in order to work with WpMVC routing:

  1. set method
/** * Define an object or a value in the container. * * @param string $name Entry name * @param mixed $value Value, define objects */ public function set(string $name, $value) {}
  1. get method
/** * Returns an entry of the container by its name. * * @template T * @param string|class-string<T> $name Entry name or a class name. * * @return mixed|T */ public function get($name) {}

Installation

composer require wpmvc/routing

Configuration

  1. Your plugin must include a routes folder. This folder will contain all of your plugin’s route files.

  2. Within the routes folder, create two subfolders: ajax and rest. These folders will contain your plugin’s route files for AJAX and REST requests, respectively.

  3. If you need to support different versions of your routes, you can create additional files within the ajax and rest subfolders. For example, you might create v1.php and v2.php files within the ajax folder to support different versions of your AJAX routes.

  4. Folder structure example:

routes: rest: api.php v1.php v2.php ajax: api.php v1.php
  1. In your RouteServiceProvider class, set the necessary properties for your route system. This includes setting the rest and ajax namespaces, the versions of your routes, any middleware you want to use, and the directory where your route files are located. Here’s an example:
<?php namespace MyPlugin\Providers; use MyPlugin\Container; use WpMVC\Routing\Providers\RouteServiceProvider as WpMVCRouteServiceProvider; class RouteServiceProvider extends WpMVCRouteServiceProvider { public function boot() { /** * Set Di Container */ parent::$container = new Container; /** * Set required properties */ parent::$properties = [ 'rest' => [ 'namespace' => 'myplugin', 'versions' => ['v1', 'v2'] ], 'ajax' => [ 'namespace' => 'myplugin', 'versions' => [] ], 'middleware' => [], 'routes-dir' => ABSPATH . 'wp-content/plugins/my-plugin/routes' ]; parent::boot(); } }
  1. Finally, execute the boot method of your RouteServiceProvider class using the init action hook:
add_action('init', function() { $route_service_provider = new \MyPlugin\Providers\RouteServiceProvider; $route_service_provider->boot(); });

That’s it! Your plugin is now configured with the WpMVC Routing system.


Register Routes In Route File

Rest Route

routes/rest/api.php

Write your first route

To create your first RESTful route in WordPress, you can use the Route and Response classes from the WpMVC\Routing namespace:

<?php use WpMVC\Routing\Route; use WpMVC\Routing\Response; use WP_REST_Request; defined('ABSPATH') || exit; Route::get('user', function(WP_REST_Request $wp_rest_request) { return Response::send(['ID' => 1, 'name' => 'john']); });

In this example, we’re using the get() method of the Route class to define a GET request to the /user endpoint.

With Controller

If you prefer to use a controller for your route logic, you can specify the controller and method as an array:

Route::get('user', [UserController::class, 'index']);

Dynamic Routing

You can use dynamic routing to handle requests to endpoints with dynamic parameters.

// Required id Route::get('users/{id}', [UserController::class, 'index']); // Optional id Route::get('users/{id?}', [UserController::class, 'index']);

Route Grouping

You can group related routes together using the group() method. This allows you to apply middleware or other attributes to multiple routes at once.

Route::group('admin', function() { Route::get('/', [UserController::class, 'index']); Route::group('user', function() { Route::get('/', [UserController::class, 'index']); Route::post('/', [UserController::class, 'store']); Route::get('/{id}', [UserController::class, 'show']); Route::patch('/{id}', [UserController::class, 'update']); Route::delete('/{id}', [UserController::class, 'delete']); } ); } );

Resource Controller

Resource routing allows you to quickly assign CRUD routes to a controller with a single line of code:

Route::resource('user', UserController::class);
Actions Handled By Resource Controller
VerbURIAction
GET/usersindex
POST/usersstore
GET/users/{user}show
PATCH/users/{user}update
DELETE/users/{user}delete

Ajax Route

routes/ajax/api.php

Sometimes third-party plugins don’t load when using the WordPress rest route. To fix this issue, WpMVC provides its own custom route system: Ajax Route.

Registering an AJAX route is similar to registering a REST route, but using the Ajax class:

use WpMVC\Routing\Ajax; use WpMVC\Routing\Response; use WP_REST_Request; Ajax::get('user', function(WP_REST_Request $wp_rest_request) { return Response::send(['ID' => 1, 'name' => 'john']); });

To route to WordPress admin, your route must use a middleware named admin.


Get Api Endpoint

Use get_rest_url() to get the REST API endpoint:

$site_id = get_current_blog_id(); $namespace = 'myplugin'; $rest_route_path = get_rest_url($site_id, $namespace); $user_rest_route = $rest_route_path . '/user';

For AJAX API endpoints:

$ajax_route_path = get_site_url($site_id) . '/' . $namespace; $user_ajax_route = $ajax_route_path . '/user';

Middleware

To create a middleware, implement the Middleware interface. The handle method must return a boolean value. If it returns false, the request stops.

<?php namespace MyPlugin\App\Http\Middleware; use WpMVC\Routing\Contracts\Middleware; use WP_REST_Request; class EnsureIsUserAdmin implements Middleware { public function handle( WP_REST_Request $wp_rest_request ): bool { return current_user_can( 'manage_options' ); } }

Register your middleware in the RouteServiceProvider:

parent::$properties = [ // ... 'middleware' => [ 'admin' => \MyPlugin\App\Http\Middleware\EnsureIsUserAdmin::class ] ];

Use it in a route:

Route::get('/admin', [AdminController::class, 'index'], ['admin']);

License

WpMVC Routing is open-sourced software licensed under the MIT license .

Last updated on