A package for presenting person names
Applications often need to show a person's name in more than one format: full name, first name, initials, mention handle, sorted name, and so on. I created a package called php-person-name to keep that logic in one place.
It is based on the name_of_person gem from Basecamp. They had the same kind of problem: how do you present a person's name in different formats when you only store first and last name?
The public API is small:
php<?php$name = new PersonName::make('David Heinemeier Hansson')echo $name->full // "David Heinemeier Hansson"echo $name->first // "David"echo $name->last // "Heinemeier Hansson"echo $name->initials // "DHH"echo $name->familiar // "David H."echo $name->abbreviated // "D. Heinemeier Hansson"echo $name->sorted // "Heinemeier Hansson, David"echo $name->mentionable // "davidh"echo $name->possessive // "David Heinemeier Hansson's"
For Laravel, you can add a name attribute to your model:
php<?phpuse Webstronauts\PersonName\PersonName;class User extends Model{/*** The attributes that are mass assignable.** @var array*/protected $fillable = ['name', 'first_name', 'last_name',];/*** Return a PersonName instance composed from the `first_name` and `last_name` attributes.** @return PersonName*/public function getNameAttribute(){return new PersonName($this->first_name, $this->last_name);}/*** Sets the `first_name` and `last_name` attributes from a full name.** @param string $name* @return void*/public function setNameAttribute($name){$fullName = PersonName::make($name);[$this->first_name, $this->last_name] = $fullName ? [$fullName->first, $fullName->last] : [null, null];}}
Now the model stores first_name and last_name, while name gives you the formatted versions:
php<?php$user = new User(['first_name' => 'Robin', 'last_name' => 'van der Vleuten'])echo $user->name->full // Robin van der Vleuten
It is a small helper, but I end up needing this kind of formatting in many applications. The package is available on GitHub.