Twine is a simple string manipulation library with an expressive, fluent syntax.
PHP's built-in string functions are plentiful and work fine for one-off string operations. However, once you have to spend more than a few cycles working with strings in PHP the minor annoyances of the methods can become glaring problems that make them a pain to read and use.
Consider the following snippet of code for a moment.
$contents = file_get_contents('garbage.bin'); return str_replace("\n", '<br>', wordwrap(base64_encode($contents), 80)));
With a little analysys we can determine that this code does the following:
The main issue with this code is that the order of operations is
"inside out". That is to say that the order in which things happen to
the data starts with the inner-most function
base64_encode) and ends with the
outer-most function (
This results in the way we read the code being backwards.
Additionally, the parameters of the functions become disconnected from
the functions themselves. This makes it difficult to tell which function
a paramter belongs to (does that
base64_encode?). Sure it may not seem
like a major issue but imagine if every method had multiple parameters
or if we split the code to multiple lines.
These problems aren't insurmountable. We could even rewrite the snippet to address these issues specifically.
$contents = file_get_contents('garbage.bin'); $base64 = base64_encode($contents); $wrapped = wordwrap($base64, 80); return str_replace("\n", '<br>', $wrapped);
This solves the "inside out" problem and brings the disconnected parameter much closer to the calling method but we've doubled the line count and introduced several short-lived, temporary variables.
Of course neither of these snippets are inherently bad and both work perfectly fine. However, don't you think we can do better.
Twine takes an object-oriented approach to making string manipulation and comparisons easy and readable. With Twine every string is an object. This gives you power and flexibility that native strings do not have in PHP. Using Twine we can re-write the snippet like so:
$string = new Twine\Str(file_get_contents('garbage.bin')) return $string->base64()->wrap(80)->replace("\n", '<br>');
Now doesn't that read better? With Twine we've solved the "inside out" problem, brought all parameters inline with their methods AND reduced the overall ammount of code. This is a win-win!
So what are you waiting for?! Get started with Twine!