2

I have rather a general question that would help me to undestand using services in Drupal 8+ and when it is worth to do so.

I have found a useful method createFromRoute which is part of

namespace Drupal\Core;

It is defined in Link.php file.

I have found plethora of examples in code when it is just called like this

Link::createFromRoute(... parameters here)

But, is calling this method like that a good practice? Should't this be somehow used as a service?

Why yes/no?

1 Answer 1

1

The \Drupal\Core\Link class is not used to implement a service and its createFromRoute() method is static. The only way to call it is like CommentBreadcrumbBuilder::build() does, for example.

$breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));

You could also directly create an instance of the Link class, as that same method does.

$breadcrumb->addLink(new Link($entity->label(), $entity->toUrl()));

Link::__construct() requires the text to show in the link and the URL, differently from Link::createFromRoute() which requires the text to show in the link and the route name.
(This means that, when you are creating the link from a route, Link::createFromRoute() is the method you want to use.)

1
  • Thank you for the explanation. Now this is finally clear to me!
    – Adamssef
    May 21, 2023 at 18:31

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.