您可以执行以下操作来检索路径参数:在这种情况下,我想将/ rest /之后的所有内容检索为字符串数组。
您的yourmodule.routing.yml文件应如下所示。
yourmodule.rest:
path: /rest/{path_parms}
defaults:
_controller: 'Drupal\yourmodule\Controller\YourController::response'
_title: 'Rest API Title'
requirements:
path_params: '^[^\?]*$'
_permission: 'access content'
或在path \ to \ yourmodule \ src \ Routing \ RouteProvider.php中
/**
* @file
* Contains \Drupal\yourmodule\Routing\RouteProvider.
*/
namespace Drupal\yourmodule\Routing;
use Symfony\Component\Routing\Route;
/**
* Defines dynamic routes.
*/
class RouteProvider
{
/**
* Returns all your module routes.
*
* @return RouteCollection
*/
public function routes()
{
$routes = [];
// This route leads to the JS REST controller
$routes['yourmodule.rest'] = new Route(
'/rest/{path_params}',
[
'_controller' => '\Drupal\yourmodule\Controller\YourController::response',
'_title' => 'REST API Title',
],
[
'path_params' => '^[^\?]*$',
'_permission' => 'access content',
]
);
\Drupal::service('router.builder')->setRebuildNeeded();
return $routes;
}
}
接下来,如下所示将Path处理器添加到模块中。路径\到\您的模块\ src \ PathProcessor \ YourModulePathProcessor.php
namespace Drupal\yourmodule\PathProcessor;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
class YourModulePathProcessor implements InboundPathProcessorInterface {
public function processInbound($path, Request $request) {
// If a path begins with `/rest`
if (strpos($path, '/rest/') === 0) {
// Transform the rest of the path after `/rest`
$names = preg_replace('|^\/rest\/|', '', $path);
$names = str_replace('/',':', $names);
return "/rest/$names";
}
return $path;
}
}
最后,在您的控制器中,执行以下操作:path \ to \ yourmodule \ src \ Controller \ YourController.php
namespace Drupal\yourmodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
/**
* Controller routines for test_api routes.
*/
class YourController extends ControllerBase {
/**
* Callback for `rest/{path_params}` API method.
*/
public function response(Request $request) {
$params = explode(':', $request->attributes->get('path_params'));
// The rest of your logic goes here ...
}
}