This post quickly shows the basic usage of WordPress Plugin and Composer. We are to use a PHP library within our own already existing WordPress Plugin.
Composer
We can use Composer with a WordPress plugin. The composer is a dependency manager for PHP. Before using it, we need to install it. Please see the Getting Started page. Depending on our operating system, go through the appropriate installation guide. Then, we will use the PHP library random-lib.
Run the following command in Windows within some directory.
1 | composer require ircmaxell/random-lib |
The command will create a vendor directory and composer.json and composer.lock files.
1 2 3 4 5 6 7 8 9 10 | C:\Users\karldev\Desktop\composer-demo>composer require ircmaxell/random-lib Using version ^1.2 for ircmaxell/random-lib ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 2 installs, 0 updates, 0 removals - Installing ircmaxell/security-lib (v1.1.0): Downloading (100%) - Installing ircmaxell/random-lib (v1.2.0): Downloading (100%) Writing lock file Generating autoload files |
The structure of the vendor directory is as follows. Later, we will copy the vendor directory created by Composer to our WordPress Plugin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | C:\USERS\KARLDEV\DESKTOP\COMPOSER-DEMO └───vendor ├───composer └───ircmaxell ├───random-lib │ ├───lib │ │ └───RandomLib │ │ ├───Mixer │ │ └───Source │ └───test │ ├───Mocks │ │ └───Random │ ├───Unit │ │ └───RandomLib │ │ ├───Mixer │ │ └───Source │ └───Vectors │ └───Random └───security-lib ├───lib │ └───SecurityLib │ └───BigMath └───test ├───Mocks └───Unit └───Core └───BigMath |
WordPress Plugin
As stated earlier, our plugin is an existing WordPress plugin that is still in the early development stage. We just want to use a PHP library in a WordPress Plugin.
With the PHP library downloaded, copy the vendor directory to a subdirectory within our WordPress Plugin location.
Then, we need to include the file autoload.php into our WordPress Plugin main PHP file.
1 2 3 | ... include_once( plugin_dir_path( __FILE__ ) .'lib/vendor/autoload.php' ); ... |
The following are sample codes using the library. The variable $randomString will contain a random String value of 10 characters using a, b, c, d, e, and f.
1 2 3 4 5 | ... $factory = new RandomLib\Factory; $generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM)); $randomString = $generator->generateString(10, 'abcdef'); ... |
Please note secure coding is not taken into consideration in this post.