What is the replacement of drupal_match_path() in Drupal 8? The following function is removed from Drupal 8. How can I achieve same functionality in Drupal 8?

function drupal_match_path($path, $patterns) {
  $regexps = &drupal_static(__FUNCTION__);

  if (!isset($regexps[$patterns])) {
    // Convert path settings to a regular expression.
    // Therefore replace newlines with a logical or, /* with asterisks and the <front> with the frontpage.
    $to_replace = array(
      '/(\r\n?|\n)/', // newlines
      '/\\\\\*/', // asterisks
      '/(^|\|)\\\\<front\\\\>($|\|)/', // <front>
    $replacements = array(
      '\1' . preg_quote(config('system.site')->get('page.front'), '/') . '\2',
    $patterns_quoted = preg_quote($patterns, '/');
    $regexps[$patterns] = '/^(' . preg_replace($to_replace, $replacements, $patterns_quoted) . ')$/';
  return (bool) preg_match($regexps[$patterns], $path);

New PathMatcher service reports that the path.matcher service was introduced to deprecate most procedural functions in the path.inc file with its methods.
In particular, the equivalent of $path_matches = drupal_match_path($path, $patterns); is the following code.

$path_matches = \Drupal::service('path.matcher')->matchPath($path, $patterns);

The same service is used to check if the currently viewed page is the front page.

$is_front = \Drupal::service('path.matcher')->isFrontPage();

As usual, injecting the dependency is preferred over calling \Drupal::service().

  • Is there any need to include '@path.matcher' service in mymodule.service.yml? – Sugandh Khanna Sep 16 '16 at 6:00
  • If you have a service that depends on path.matcher, you can declare it as dependency. Then the question would be "Do I need to create a service?" That depends from the code you are writing. Notice also that, if you have a form, you can inject its dependencies too. – kiamlaluno Sep 16 '16 at 6:10
  • How can I inject this dependency ? – Sugandh Khanna Sep 16 '16 at 6:10
  • It depends from the code you are using. That is a different question, though. – kiamlaluno Sep 16 '16 at 6:11
  • For database operations I used '@database' as argument in service.yml. Can I inject this service as well?I have a simple form with CRUD operations. – Sugandh Khanna Sep 16 '16 at 6:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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