Working With PHP

Developing PHP, using the files in your plugin.

If you enable the “Composer and PHP Tests” option in the “Manage Features” section of the plugin editor, you will be able to add testing, a PHP autoloader and a code linter. To use these features in your plugin you will need to run composer install

Setting Up The PHP Options For The Plugin

When creating a plugin, if you enable “Composer & PHP Tests” setting, the builder will take you to the options for those settings, which looks like this:

You must select a PHP namespace. PHP namespaces should be camel-cased, so they will work with the PSR-4 standard correctly. Your plugin will include a composer.json file. You can customize the autoloader in that file, if needed.

You can enable two types of tests, both uses phpunit. The first option is “Unit Tests” these tests are not run in an environment with WordPress or even MySQL loaded. The second option is “WordPress Integration Tests,” which do run with WordPress and MySQL loaded.

There is also an option to enable a linter, which will automatically format your code. These are the options for the linters:

I promise to add support for WPCS and phpstan soon.

Working With Your Plugin

After you download the development build of your plugin, you can open the files in vsCode or any other IDE. If you enabled the PHP features, you will need to run “composer install” first. Your plugin’s README file includes insturctions.

Using Namespaces

https://pluginmachine.com/doc/working-with-php-namespaces/

Automated Tests

There are two types of tests you might have added “unit” and “WordPress”. The phpunit polyfills package by Yoast will be installed for both test types.

Writing And Running Unit Tests

Before running the tests, you will need to run “composer install”. The README of your plugin will include the command to run these types of tests.

The unit tests will be located in the directory “tests/Unit”. You will find some example tests there. These tests do not have WordPress, you will see examples of how to use Brain Monkey for mocking.

Writing And Running WordPress Tests

The unit tests will be located in the directory “tests/Integration”. You will find some example tests there. When you enable these tests, the generated docker-compse file has a container for running these tests. The README of your plugin will include the command to enter the container, and once inside, the one command to run the tests.

There is no additional setup needed.

Linter

The README of your plugin will include the command to run the linter. Your plugin will include a phpcs.xml file, which defines the PHP code style. You can customize that file as needed.