I’m developing a working package of plugins and libraries in an attempt to create a more flexible routing in WordPress based around the possibility offered by the WP Router plugin and some wrapping classes I’ve created.
This article is the seventh in a series and skimming the previous ones will allow some deeper understanding of the problem at hand.
A first simple user story
To have a clear objective to code to I will implement a first user story
As a WordPress user I want to be able to add a page showing the content of a route endpoint to the navigation menus. An example would be the possibility to add a page showing the
/posts
route content to the navigation menus.
The process involved is composed of the following steps:
- in a plugin adding routes the developer is given the possibility to assign meta information to each route
- the
\tad\wrappers\WP_Router\Route
class will allow hooking before and after routes are added using WP Router - the plugin will hook into one of those hooks to persist some routes to the database based on the meta information
- some pages will be programmatically added to the available pages and the user will be able to add those to the navigation menus
Assigning meta information to a route
That’s a simple addition to the \tad\wrappers\WP_Router\Route
class and I’ve added the with
method
/**
* Allows adding additional information to a route.
*
* Additional arguments will be ignored by WP Router.
*
* @param string $key The key for the information to add.
* @param mixed $value The value for the information to add.
*
* @return Route The calling instance.
*/
public function with($key, $value);
and an usage example, to add a description, is
Route::get('/hello', function(){
echo "Hello there!"
})->withTemplate('page')
->with('description', 'The hello route.');
Adding an hook
To allow persistence of routes I need to either delegate the \tad\wrappers\WP_Router\Route
class with the task or to create an hook in it to allow for third party handling of the process.
The first solution seems to me a violation of the Single responsibility principle and will hence go with the second solution.
I’ve modified the \tad\wrappers\Wp_Router\Route::generateRoutes
method to
public static function generateRoutes(\WP_router $router, FunctionsAdapter $f = null)
{
if (is_null($f)) {
$f = new Functions();
}
$f->do_action('route_before_adding_routes', self::$routes);
foreach (self::$routes as $route => $args) {
$router->add_route($route, $args);
}
$f->do_action('route_after_adding_routes', self::$routes);
}
where those $f
in code are to allow for TDD to be applied and come from tdd-helpers. I’ve also added the general purpose with
method to allow for appending additional arguments, ignored by WP Router, to the route.
Next
Point 3 and 4 of the list above.