Stylized line drawing of mark playing the flute

Recreating Laravel Accessor attributes

Laravel models have a great feature called Accessors.

The basic idea is that you define a class method like this

public function getFullNameAttribute() {
	return "{$this->first_name} {$this->last_name}";
}

Then doing something like $myClass->full_name actually executes the getFullNameAttribute function.

Obviously Laravel's model class is much more full-featured and can do a lot more.

That said, it's pretty easy to mimic Laravel's Accessor functionality.

The first piece is a simple Str class which turns snake-case names into camel-case names. In a real Laravel application, you're better off using the Laravel Helpers.

Then we're going to implement a simple Model class

Now we can create a simple Person class which extends our Model

In this case, we have two public properties for first & last name and then we've defined a full_name accessor.

To tie it all together, we can use our new class like this

The above script will output

First name: Mark
Last name: Biek
Full name: Mark Biek