Updating deprecated \Drupal::url() calls in Drupal 8
This covers only the most common use cases.
A little more information
If you are using additional arguments
\Drupal::url() method seems to be a wrapper for the new service and uses the same arguments as the new service in the same order. You should be able to pass them all in the same way.
\Drupal::url('entity.node.canonical', ['node' => 1], ['query' => ['test_key' => 'test_value']], FALSE);
\Drupal::service('url_generator')->generateFromRoute('entity.node.canonical', ['node' => 1], ['query' => ['test_key' => 'test_value']], FALSE);
More complex updates
If you would like to use dependency injection, you will need to inject the service
Unfortunately, dependency injection patterns for services, controllers, and plugins (example: block plugin) are different. See https://github.com/damontgomery/d8_examples/tree/develop/d8e_service_dependency_injection for some examples of how dependency injection looks for these.
We have a set of examples as part of the Drupal Rector
rector_examples module. See https://github.com/palantirnet/drupal-rector/tree/master/rector_examples.
Automating updates with Drupal Rector
Drupal Rector is an open source tool built using Rector which can help automate this deprecation as well as other common deprecations.
For more information, see https://github.com/palantirnet/drupal-rector.
What is covered by the rector
Drupal Rector currently replaces static calls to
\Drupal::url() as shown above.
Drupal Rector does not inject services into classes.
This code was deprecated in Drupal 8.0.0, but no change record was found which describes the purpose of the change.
Most likely, this code was deprecated to increase the ability to unit test code. Similar functionality was removed in Drupal and the recommendation was to use services whenever possible.
\Drupal::url() code provided an alternate way to generate a URL object using a common method of using a route. This is part of a set of ways to generate url objects such as
\Drupal\Core\Url::fromUserInput(). Moving forward, developers will need to select the appropriate method for each use case.
This code was deprecated in Drupal 8.0.0, but no change record was found.
This change record looks to be a close match although it does not name the
\Drupal::url() method explicitly, https://www.drupal.org/node/2046643.
Credits and thank yous
Thank you to Dan Montgomery for leading Drupal Rector development to support this deprecation.
Thank you to Palantir.net for sponsoring this development.