Getting down and dirty with Twine.
Using Twine is simple, once installed start by importing the library.
<?php
use PHLAK\Twine;
// ...
Next you must instatiate a Twine object. There are multiple ways to accomplish this. No one method is better than the rest so choose the one that best suits you and your project's needs. You may even use multiple instantiation methods within the same project or file.
The default method of instantiation is to simply new up a
Twine\Str
object passing your string
as the first and only parameter.
$string = new Twine\Str('john pinkerton');
When passing a non-string parameter to theTwine\Str
object it will be cast as a string internally.
You may also instantiate a Twine\Str
object statically via the make()
method.
$string = Twine\Str::make('john pinkerton');
Twine also comes with a global str()
helper method. The method takes a string as the only parameter and
returns a Twine\Str
object.
$string = str('john pinkerton');
Once you have a concrete Twine\Str
instance you may treat it like any other string. This includes echoing
it or using any of PHPs built in string functions against it.
echo $string; // Echos 'john pinkerton'
str_shuffle($string) // Returns something like 'enoipo ktnjhnr'
strlen($string); // Returns 14
Keep in mind that a Twine\Str
object
is not an actual a string primitive.
is_string($string); // Returns false
$string === 'john pinkerton' // Returns false
At this point you're ready to start using Twine by calling any of it's many built in methods.
$string->substring(5, 4); // Returns 'pink'
$string->uppercaseWords(); // Returns 'John Pinkerton'
$string->words(); // Returns ['john', 'pinkerton']
You can even chain these together for advanced functionality and ease of use.
$string->substring(5, 4)->equals('pink'); // Returns true
$string->prepend('mr. ')->uppercaseWords(); // Returns 'Mr. John Pinkerton'
See the Method Chaining section for more info and examples.
When using the static make()
method or
the str()
helper you can chain methods
immediately after in a single line.
Twine\Str::make('john pinkerton')->uppercaseWords();
str('john pinkerton')->uppercaseWords();