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

Plugin Unit Testing in WordPress

I'll admit that I have been pretty hit-and-miss with testing on projects over the course of my career. That said, I've been trying to be a little more consistent about it.

For Laravel projects, it's real easy since PHPUnit integration is built into Laravel right out of the box.

I also do a fair amount of WordPress and being able to unit test plugins and other functionality would be very handy.

While the setup is a little confusing at first, WordPress also comes with great tools for testing.

The official WordPress testing documentation is good and the wp cli can be used to build out most of the test scaffolding for you.

I also found these resources to be helpful

But there's one thing I don't like about how WordPress handles testing.

They operate under the assumption that there will be a separate test database that gets completely wiped and reset each time the tests are run. While I understand the point behind, that approach doesn't work for a lot of my use-cases.

There are several projects with very large databases and it's easier and makes more sense for me to run the unit tests against my local development copy.

To that end, I've started a Github project: https://github.com/markbiek/wordpress-dev which is a clone of http://develop.svn.wordpress.org/trunk/.

The only difference is, my version doesn't delete any data when the tests are run. We've just removed the contents of the _delete_all_data and _delete_all_posts functions in functions.php.

If you can, I'd recommend sticking with the official WordPress way of testing. But hopefully this will be useful to some other people.

All Posts