Changelog:

Drupal_get_path() and drupal_get_filename() have been deprecated. Use an extension type-specific  \Drupal\Core\Extension\ExtensionList::getPath() and \Drupal\Core\Extension\ExtensionList::getPathname() instead where possible. You can use \Drupal::service('extension.path.resolver')->getPath()/getPathname() and dynamically pass in the extension type as the first parameter.

Before:

drupal_get_path('theme', 'MYTHEME') . '/css/main.css';

After:

\Drupal::service('extension.list.theme')->getPath('MYTHEME')

Background

drupal_get_path() and drupal_get_filename() have been deprecated. Use an extension type-specific  \Drupal\Core\Extension\ExtensionList::getPath() and \Drupal\Core\Extension\ExtensionList::getPathname() instead where possible. You can use \Drupal::service('extension.path.resolver')->getPath()/getPathname() and dynamically pass in the extension type as the first parameter.

These methods will throw:

  • \Drupal\Core\Extension\Exception\UnknownExtensionException if the extension is not found.
  • \Drupal\Core\Extension\Exception\UnknownExtensionTypeException if the extension type is not found.

drupal_get_path()

Before After
drupal_get_path('module', 'node') \Drupal::service('extension.list.module')->getPath('node')
drupal_get_path('theme', 'seven') \Drupal::service('extension.list.theme')->getPath('seven')
drupal_get_path('profile', 'standard') \Drupal::service('extension.list.profile')->getPath('standard')

If you want to specify the type dynamically you can use:

Before After
drupal_get_path('module', 'node') \Drupal::service('extension.path.resolver')->getPath('module', 'node')

drupal_get_filename()

Before After
drupal_get_filename('module', 'node') \Drupal::service('extension.list.module')->getPathname('node')
drupal_get_filename('theme', 'seven') \Drupal::service('extension.list.theme')->getPathname('seven')
drupal_get_filename('profile', 'standard') \Drupal::service('extension.list.profile')->getPathname('standard')

If you want to specify the type dynamically you can use:

Before After
drupal_get_filename('module', 'node') \Drupal::service('extension.path.resolver')->getPathname('module', 'node')

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!