@@ -453,6 +453,55 @@ 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+
500+ .. versionadded :: 5.1
501+
502+ The :class: `Symfony\\ Component\\ String\\ LazyString ` class was introduced
503+ in Symfony 5.1.
504+
456505Slugger
457506-------
458507
0 commit comments