Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2f485d1

Browse files
committed
Merge branch '6.2' into 6.3
* 6.2: Remove the versionadded directive [String] Add `LazyString` documentation
2 parents fa48443 + 7fbb282 commit 2f485d1

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

components/string.rst

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,50 @@ letter A with ring above"*) or a sequence of two code points (``U+0061`` =
453453
u('å')->normalize(UnicodeString::NFD);
454454
u('å')->normalize(UnicodeString::NFKD);
455455

456+
Lazy-loaded Strings
457+
-------------------
458+
459+
Sometimes, creating a string with the methods presented in the previous sections
460+
is not optimal. For example, consider a hash value that requires certain
461+
computation to obtain and which you might end up not using it.
462+
463+
In those cases, it's better to use the :class:`Symfony\\Component\\String\\LazyString`
464+
class that allows to store a string whose value is only generated when you need it::
465+
466+
use Symfony\Component\String\LazyString;
467+
468+
$lazyString = LazyString::fromCallable(function () {
469+
// Compute the string value...
470+
$value = ...;
471+
472+
// Then return the final value
473+
return $value;
474+
});
475+
476+
The callback will only be executed when the value of the lazy string is
477+
requested during the program execution. You can also create lazy strings from a
478+
``Stringable`` object::
479+
480+
class Hash implements \Stringable
481+
{
482+
public function __toString(): string
483+
{
484+
return $this->computeHash();
485+
}
486+
487+
private function computeHash(): string
488+
{
489+
// Compute hash value with potentially heavy processing
490+
$hash = ...;
491+
492+
return $hash;
493+
}
494+
}
495+
496+
// Then create a lazy string from this hash, which will trigger
497+
// hash computation only if it's needed
498+
$lazyHash = LazyString::fromStringable(new Hash());
499+
456500
Slugger
457501
-------
458502

0 commit comments

Comments
 (0)