Can I use traits? Or will I cut out a large portion of the community?

In contrast to Ben, I think you can use traits if you have to. Make sure to check for PHP version during plugin installation. Do not let your users run into some obscure PHP errors.

And don’t look at the wp.org stats too long. The version stats include abandoned installations which don’t matter for new plugins. Only 15% are actually kept up to date. The old sites influence the statistics heavily.

But.

Traits are rarely the proper solution for an architectural problem. If you need access to the same methods in multiple objects, use dependency injection and/or a factory.

A very simple example: Let’s say you need access to to the header data of your plugin in multiple classes. You could use a trait for that. But you shouldn’t. It is better to separate this out and create a new class.

interface Plugin_Info_Interface
{
    public function set_file( $plugin_file );

    public function __get( $name );
}
class Plugin_Info implements Plugin_Info_Interface
{
    protected $plugin_file, $data = array();

    public function set_file( $plugin_file )
    {
        $this->plugin_file = $plugin_file;
    }

    public function __get( $name )
    {
        if ( isset ( $this->data[ $name ] ) )
            return $this->data[ $name ];

        $this->data = array_merge( 
            $this->data, 
            get_file_data( $this->plugin_file, array( $name ) ) 
        );

        if ( isset ( $this->data[ $name ] ) )
            return $this->data[ $name ];

        return '';
    }
}

And now, in a class for extra information in the plugin list table you just use an instance of this separate class to get the data:

class Plugin_Table_Extra
{
    protected $plugin_info;

    public function set_header_data( Plugin_Info_Interface $plugin_info )
    {
        $this->plugin_info = $plugin_info;
    }

    public function show_git_repo()
    {
        $repo_url = $this->plugin_info->repo_url;

        if ( empty ( $repo_url ) )
            return;

        // create a link
    }
}

Easier to read, to test and to keep backwards compatible.

Leave a Comment