Score:2

Using Drupal's Core classes as services

in flag

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?

Score:1
us flag

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.)

Adamssef avatar
in flag
Thank you for the explanation. Now this is finally clear to me!
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.