DocumentationServices ProviderAutoload Service Providers

Autoload Service Providers

In the config/plugin.php file, you might have noticed the providers key. It is used to load your custom providers on the load of a plugin.

config/plugin.php
  /*
  |--------------------------------------------------------------------------
  | Autoloaded Service Providers
  |--------------------------------------------------------------------------
  |
  | The service providers listed here will be automatically loaded on the
  | init of your plugin. Feel free to add your own services to
  | this array to grant expanded functionality to your applications.
  |
  */
 
  'providers' => [ 'YourNamespace\Providers\YourServiceProvider' ],

PHP Bones Command

Using the PHP Bones make:provider Bones command, we can quickly create a Service Provider.

Typical Service Provider

Let me show you a typical service provider.

plugin/Providers/YourServiceProvider.php
<?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;
  }
 
}