Autoload Service Providers
This document explains how to create and autoload service providers in WP Bones. Service providers are used to register services, actions, filters, and other necessary components. It provides steps to create a new service provider using the php bones make:provider MyProvider
command and how to manually create one. The document also covers editing the service provider bootstrap and demonstrates how to use service providers to add plugin row data in the plugin list view.
Overview
WP Bones allows you to create your own service providers. Service providers are used to register services, actions, filters, and other services you require.
Create a new Service Provider
You may create your own service provider by following the steps below:
php bones make:provider MyProvider
By default, the new provider will be created in the plugins/Providers
directory.
Of course, you may create your Service Provider manually and in any directory you prefer. You have to change the namespace accordingly.
Edit the Service Provider bootstrap
<?php
namespace YourNamespace\Providers;
use YourNamespace\WPBones\Support\ServiceProvider;
class YourServiceProvider extends ServiceProvider
{
public function register()
{
// TODO
}
}
The service providers are useful because they are loaded at the start (init) of the plugin. For example, you may use them to add the plugin row data in the plugin list view:
public function register()
{
// plugin list
add_action( 'plugin_action_links_' . WPKirk()->pluginBasename, [ $this, 'plugin_action_links' ], 10, 4 );
}
public function plugin_action_links( $links )
{
$main = '<a href="' . menu_page_url( 'wp_kirk_slug_menu', false ) . '">' . __( 'Main' ) . '</a>';
$settings = '<a href="' . menu_page_url( 'wp_kirk_slug_menu-settings', false ) . '">' . __( 'Settings' ) . '</a>';
array_unshift( $links, $main, $settings );
return $links;
}
Plugin instance pointer
As you know, you can get the plugin instance by using WPKirk()
global function or YourNamespace()
. Anyway, in the service provider, you’ll be able to get the plugin instance by using $this->plug
property.
<?php
namespace YourNamespace\Providers;
use YourNamespace\WPBones\Support\ServiceProvider;
class YourServiceProvider extends ServiceProvider
{
public function register()
{
// TODO
}
public function myMethod()
{
$plugin = $this->plugin;
}
}
Load the Service Provider
The service providers are loaded through the config/plugin.php
file.
/*
|--------------------------------------------------------------------------
| Autoload Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| initialization of your plugin. Feel free to add your own services to
| this array to provide expanded functionality to your applications.
|
*/
"providers" => [
"YourNamespace\Providers\YourServiceProvider",
],
Of course, you can add one or more classes in the providers
array.