3

I'm finding that these two PHP snippets yield the same result:

$arr['query']['confirm'] = 'y';
$text = t('Click here.');
$url = new Url('my_route.import', [], $arr); // Three arguments.
$link = Link::fromTextAndUrl($text, $url)->toString();

and

$arr['confirm'] = 'y'; // No "query" key.
$text = t('Click here.');
$url = Url::fromRoute('my_route.import', $arr); // Two arguments.
$link = Link::fromTextAndUrl($text, $url)->toString();

Is there any reason to prefer one approach over the other? Which is the more typical approach? Is there some general PHP rule of thumb that might apply, such as... always use a method on the class instead of instantiating an object with "new" whenever possible?

  • 2
    Not really sure if I agree with that statement. The Url::__construct method is thin; it just sets a few protected variables. The Url::fromRoute method essentially just invokes the constructor to return a new Url object. – mpdonadio Mar 10 at 16:51
  • Ok, I removed it. Thanks for the clarification. – Jaypan Mar 10 at 20:30
3

From the documentation for the Url class:

In most cases, use Url::fromRoute() or Url::fromUri() rather than constructing Url objects directly in order to avoid ambiguity and make your code more self-documenting.

So, generating a new Url object from a static method is preferred.

| improve this answer | |
  • 2
    This is part of the factory vs constructor arguments in the OO world. Using the factory is more in line with the "program to the API and not the implementation" line of thought. – mpdonadio Mar 10 at 18:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.