我应该如何使用composer自动加载WordPress插件类进行测试?

I'm working in a WordPress plugin, following the WordPress Coding Standards.

This is the current structure for the plugin:

.
├── includes
├── languages
├── views
├── class-plugin-admin.php
├── class-plugin.php
└── plugin.php

That said, I would like to use the Composer autoloader to load both classes (for unit testing purposes).

Today I've been loading them like this:

"autoload-dev": {
    "files": [
        "class-plugin.php",
        "class-plugin-admin.php"
    ]
}

However, not sure if this one would be the best way to do it.

So here are the questions:

  • Should I move my classes to a subdirectory in the plugin?
  • Which one would be the best way to load them via composer?

Should I move my classes to a subdirectory in the plugin?

You don't need to, but you can. It definitely makes developing the plugin a lot easier, and I would suggest to do so.

As you indicated, you probably already have tests, so why not go ahead and adjust the structure to something like this:

.
├── includes
├── languages
├── src
│   ├── Plugin.php
│   └── PluginAdmin.php
├── test
│   ├── PluginAdminTest.php
│   ├── PluginTest.php
│   └── phpunit.xml
├── views
├── composer.json
└── plugin.php

Note I adjusted the class names, because ideally, you probably want to use some way of PSR-4 autoloading for your classes.

For reference, see:

Which one would be the best way to load them via composer?

This largely depends on whether you want to move your classes to a sub-directory or not. Let's assume you did, and let's assume you were using Toally\Amazing as a namespace prefix for your classes:

PSR-4

Use the PSR-4 autoloader:

{ 
    "autoload-dev": {
        "Totally\\Amazing\\": "src/"
    }
}

For reference, see:

Classmap

List the directory which contains the classes:

{
    "autoload-dev": {
        "classmap": [
            "src/",
        ]
    }
}

For reference, see:

Decide for yourself which makes the most sense for you!

Autoloading in production

As you can see, I use the autoload-dev section to indicate that composer autoloading is only relevant for development, not for production. You would still need to

  • require classes in plugin.php or
  • implement autoloading for your classes in plugin.php

Take a look at

which provides a corresponding example for autoloading classes from your plugin.