Drupal - How do I implement the equivalent of hook_url_inbound_alter()?
The PathProcessorAlias()
class is probably your best example.
- Create a module with a class the implements
InboundPathProcessorInterface
. - Create the service definition in your module.
- Make sure your service has the
path_processor_inbound
service tag. This will mark it for collection and tie it to the path processor. You may need to play with the priority to change where it runs.
Your class will need to have some injected dependencies for looking up the entity. EntityManager()
got broken up recently, and I forget which ones you will really need. You may also need/want the PathValidator()
service.
Here is a concrete example of what code needs to be written so that when hitting a url such as :
www.my-website.com/my-pretty-alias
You actually display the content of the following page :
www.my-website.com/my-technical-needed-path/such-as/node/8
but my-pretty-alias is displayed in the url bar
In my_module.services.yml file :
services:
my_module.my_service_identifier:
class: Drupal\my_module\Service\MyServiceName
tags:
- { name: path_processor_inbound }
In my_module/src/Service/MyServiceName.php file :
<?php
namespace Drupal\my_module\Service;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
class MyServiceName implements InboundPathProcessorInterface {
public function processInbound($path, Request $request) {
if (strpos($path, '/my-pretty-alias') === 0) {
$path = preg_replace('#^/my-pretty-alias#', '/my-technical-needed-path/such-as/node/8', $path);
}
return $path;
}
}