5

I'm working on a module which will resolve URLs to entities by altering inbound URLs so that if they contain an entity ID with following pattern "-{entity_id}" user will be redirected to correct URL.

A working example of the above:

Final URL:

I researched for a while; I found out there was hook_url_inbound_alter() in Drupal 7 which could solve this problem.

I also found that there is InboundPathProcessorInterface in Drupal 8.

I thought about implementing InboundPathProcessorInterface and use it in EventSubscriberInterface implementation which will subscribe on KernelEvents::REQUEST.

I wonder if this approach is correct. Are there any other ways of doing this in Drupal 8?

1
  • Have a look at \Drupal\Core\ParamConverter\EntityConverter
    – user21641
    Commented Feb 12, 2016 at 11:24

2 Answers 2

15

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.

1
  • 1
    Hi @MPD, thank you for your answer, it worked as I wanted :)
    – otarza
    Commented Feb 15, 2016 at 13:47
2

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;
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.