How to create a new Plugin type using Plugin API of Drupal 8?
Create a new Plugin Type in Drupal 8
Example from Drupal 8 example module, Thank you.
See the Drupal 8 'Example' contrib module for full details and source
Module name : 'plugin_type_example'
1. Define the plugin type as service in the service.yml file
Example:
File plugin_type_example.services.yml
services:
# The machine name of the service. This is the string that must be passed to
# Drupal::service() to get the instantiated plugin manager.
plugin.manager.sandwich:
# This tells the service container the name of our plugin manager class.
class: Drupal\plugin_type_example\SandwichPluginManager
arguments: ['@container.namespaces', '@cache.default', '@module_handler']
2. Create an interface for the new plugin type
Example:
File src/SandwichInterface.php
<?php
/**
* @file
* Provides Drupal\plugin_type_example\SandwichInterface.
*/
namespace Drupal\plugin_type_example;
/**
* An interface for all Sandwich type plugins.
*/
interface SandwichInterface {
/**
* Provide a description of the sandwich.
* @return string
* A string description of the sandwich.
*/
public function description();
}
3. Create a new Plugin Manager using drupal DefaultPluginManager
Example
File : src/SandwichPluginManager.php
<?php
/**
* @file
* Contains \Drupal\plugin_type_example\SandwichPluginManager.
*/
namespace Drupal\plugin_type_example;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
/**
* Manages sandwich plugins.
*/
class SandwichPluginManager extends DefaultPluginManager {
/**
* Creates the discovery object.
*
* @param \Traversable $namespaces
* An object that implements \Traversable which contains the root paths
* keyed by the corresponding namespace to look for plugin implementations.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* Cache backend instance to use.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler to invoke the alter hook with.
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
// This tells the plugin system to look for plugins in the 'Plugin/Sandwich' subfolder inside modules' 'src' folder.
$subdir = 'Plugin/Sandwich';
// The name of the interface that plugins should adhere to. Drupal will enforce this as a requirement.
$plugin_interface = 'Drupal\plugin_type_example\SandwichInterface';
// The name of the annotation class that contains the plugin definition.
$plugin_definition_annotation_name = 'Drupal\Component\Annotation\Plugin';
parent::__construct($subdir, $namespaces, $module_handler, $plugin_interface, $plugin_definition_annotation_name);
// This allows the plugin definitions to be altered by an alter hook. The parameter defines the name of the hook, thus: hook_sandwich_info_alter().
$this->alterInfo('sandwich_info');
// This sets the caching method for our plugin definitions.
$this->setCacheBackend($cache_backend, 'sandwich_info');
}
}
Now Your new Plugin type is ready to use.
Create a new plugin in Drupal 8
Create a new plugin using newly creates plugin type "Sandwich"
1. Under src/Plugin/Sandwich, Create a new plugin named 'ExampleHamSandwich'
Example:
File : src/Plugin/Sandwich/ExampleHamSandwich.php
<?php
/**
* @file
* Contains \Drupal\plugin_type_example\Plugin\Sandwich\ExampleHamSandwich.
*/
namespace Drupal\plugin_type_example\Plugin\Sandwich;
use Drupal\Core\Plugin\PluginBase;
use Drupal\plugin_type_example\SandwichInterface;
/**
* Provides a ham sandwich.
*
* The ham sandwich only needs to exist within the Plugin\Sandwich namespace to be declared as a plugin. This is defined in
* \Drupal\plugin_type_example\SandwichPluginManager::__construct().
*
* The following is the plugin annotation. This is parsed by Doctrine to make the plugin definition. Any values defined here will be available in the plugin definition.
*
* This should be used for metadata that is specifically required to instantiate the plugin. Many plugin annotations can be reduced to a plugin ID, a label and perhaps a description.
*
* @Plugin(
* id = "ham_sandwich",
* foobar = @Translation("This is an example value that is defined in the annotation."),
* calories = 426,
* )
*/
class ExampleHamSandwich extends PluginBase implements SandwichInterface {
/**
* Get a description of the sandwich fillings.
*/
public function description() {
return $this->t('Ham, mustard, rocket, sun-dried tomatoes.');
}
}
Now you can yse your plugin
Example:
<?php
/**
* @file
* Contains \Drupal\plugin_type_example\Controller\PluginTypeExampleController.
*/
namespace Drupal\plugin_type_example\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\plugin_type_example\SandwichPluginManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Controller for our example pages.
*/
class PluginTypeExampleController extends ControllerBase {
protected $sandwichManager; //The sandwich plugin manager.
/**
* Constructor.
*
* @param \Drupal\plugin_type_example\SandwichPluginManager $sandwich_manager The sandwich plugin manager service. We're injecting this service so that we can use it to access the sandwich plugins.
*/
public function __construct(SandwichPluginManager $sandwich_manager) {
$this->sandwichManager = $sandwich_manager;
}
/**
* Displays a page with an overview of our plugin type and plugins.
*
* Lists all the Sandwich plugin definitions by using methods on the
* \Drupal\plugin_type_example\SandwichPluginManager class. Lists out the
* description for each plugin found by invoking methods defined on the
* plugins themselves. You can find the plugins we have defined in the
* \Drupal\plugin_type_example\Plugin\Sandwich namespace.
*/
public function description() {
$build = array();
$build['intro'] = array(
'#markup' => t("This page lists the sandwich plugins we've created. The sandwich plugin type is defined in Drupal\\plugin_type_example\\SandwichPluginManager. The various plugins are defined in the Drupal\\plugin_type_example\\Plugin\\Sandwich namespace."),
);
// Get the list of all the sandwich plugins defined on the system from the
// plugin manager.
// Note that at this point, what we have is *definitions* of plugins, not
// the plugins themselves.
$sandwich_plugin_definitions = $this->sandwichManager->getDefinitions();
// Let's output a list of the plugin definitions we now have.
$items = array();
foreach ($sandwich_plugin_definitions as $sandwich_plugin_definition) {
// Here we use various properties from the plugin definition. These values
// are defined in the annotation at the top of the plugin class: see
// ExampleHamSandwich.
$items[] = t("@id (calories: @calories, foobar: @foobar )", array(
'@id' => $sandwich_plugin_definition['id'],
'@calories' => $sandwich_plugin_definition['calories'],
'@foobar' => $sandwich_plugin_definition['foobar'],
));
}
// Add our list to the render array.
$build['plugin_definitions'] = array(
'#theme' => 'item_list',
'#title' => 'Sandwich plugin definitions',
'#items' => $items,
);
// If we want just a single plugin definition, we can use getDefinition().
// This requires us to know the ID of the plugin we want. This is set in the annotation on the plugin class: see ExampleHamSandwich.
$ham_sandwich_plugin_definition = $this->sandwichManager->getDefinition('ham_sandwich');
// To get an actual plugin, we call createInstance() on the plugin manager,
// passing the ID of the plugin we want to load. Let's output a list of the
// actual plugins.
$items = array();
// The array of plugin definitions is keyed by plugin id, so we can just use
// that to load our plugins.
foreach ($sandwich_plugin_definitions as $plugin_id => $sandwich_plugin_definition) {
// We now have a plugin! From here on it can be treated just as any other
// object: have its properties examined, methods called, etc.
$plugin = $this->sandwichManager->createInstance($plugin_id, array('of' => 'configuration values'));
$items[] = $plugin->description();
}
$build['plugins'] = array(
'#theme' => 'item_list',
'#title' => 'Sandwich plugins',
'#items' => $items,
);
return $build;
}
/**
* {@inheritdoc}
* This is dependancy injection at work for a controller. Rather than access the global service container via \Drupal::service(), it's best practice to use dependancy injection.
*/
public static function create(ContainerInterface $container) {
// Use the service container to instantiate a new instance of our controller.
return new static($container->get('plugin.manager.sandwich'));
}
}
Comments