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:
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:
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:
Use the PSR-4 autoloader:
{
"autoload-dev": {
"Totally\\Amazing\\": "src/"
}
}
For reference, see:
List the directory which contains the classes:
{
"autoload-dev": {
"classmap": [
"src/",
]
}
}
For reference, see:
Decide for yourself which makes the most sense for you!
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
plugin.php
orplugin.php
Take a look at
which provides a corresponding example for autoloading classes from your plugin.