3 namespace Drupal\Core\Routing;
5 use Symfony\Component\HttpFoundation\RedirectResponse;
8 * Wrapper methods for the Url Generator.
10 * This utility trait should only be used in application-level code, such as
11 * classes that would implement ContainerInjectionInterface. Services registered
12 * in the Container should not use this trait but inject the appropriate service
13 * directly for easier testing.
15 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
16 * Use \Drupal\Core\Url instead.
18 trait UrlGeneratorTrait {
23 * @var \Drupal\Core\Routing\UrlGeneratorInterface
25 protected $urlGenerator;
28 * Generates a URL or path for a specific route based on the given parameters.
30 * For details on the arguments, usage, and possible exceptions see
31 * \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute().
34 * The generated URL for the given route.
36 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
37 * Use \Drupal\Core\Url instead.
39 * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
41 protected function url($route_name, $route_parameters = [], $options = []) {
42 return $this->getUrlGenerator()->generateFromRoute($route_name, $route_parameters, $options);
46 * Returns a redirect response object for the specified route.
48 * @param string $route_name
49 * The name of the route to which to redirect.
50 * @param array $route_parameters
51 * (optional) Parameters for the route.
52 * @param array $options
53 * (optional) An associative array of additional options.
55 * (optional) The HTTP redirect status code for the redirect. The default is
58 * @return \Symfony\Component\HttpFoundation\RedirectResponse
59 * A redirect response object that may be returned by the controller.
61 protected function redirect($route_name, array $route_parameters = [], array $options = [], $status = 302) {
62 $options['absolute'] = TRUE;
63 $url = $this->url($route_name, $route_parameters, $options);
64 return new RedirectResponse($url, $status);
68 * Returns the URL generator service.
70 * @return \Drupal\Core\Routing\UrlGeneratorInterface
71 * The URL generator service.
73 protected function getUrlGenerator() {
74 if (!$this->urlGenerator) {
75 $this->urlGenerator = \Drupal::service('url_generator');
77 return $this->urlGenerator;
81 * Sets the URL generator service.
83 * @param \Drupal\Core\Routing\UrlGeneratorInterface $generator
84 * The url generator service.
88 public function setUrlGenerator(UrlGeneratorInterface $generator) {
89 $this->urlGenerator = $generator;