Discovering Plug in Play architecture - Exploring Successful Plug-and-Play Implementations
Tags: architecture, guide, pluginplay, softwaredevelopment
Published: 2023-12-08 21:28:19


Welcome back to our journey into the world of Plug-and-Play Architecture! In this article we study real-world examples to gain valuable insights into the diverse strategies and methodologies applied when creating Plug in Play solutions.

## Dupral 

Dupal, a popular content management system (CMS), provides a flexible and powerful plugin system that allows developers to extend and customize the platform's functionality.

### Here's how plugins work in Drupal:

- Plugins are organized into **types**, representing specific categories of functionality, such as block plugins, field formatter plugins, and authentication plugins.

-  Each plugin type has a set of **plugin definitions declared using annotations**, providing metadata and essential information about each plugin

- A **plugin manager**, a service provided by Drupal's dependency injection container, is responsible for discovering, managing, and instantiating plugins.

### Developer can:

- **Extend Plugins**: Create new plugins within an existing type to add features or customize behavior without altering the core functionality. For instance, you can create a new field formatter that adds CSS styles or markup to rendered content.

- **Decorate Plugins**: Certain plugins can be decorated by others, enhancing features without altering core behavior. It's like "wrapping" an existing plugin with additional capabilities.

- **Override Plugins:** Replace or modify existing plugins with custom implementations, useful for changing how contributed module plugins work. For example, you can override a core authentication plugin to integrate custom user authentication logic with an external system.

### Dupral Hello World example

Let's create a "Hello World" example of a custom plugin in Drupal. 

- In your Drupal installation, navigate to the `sites/all/modules` and create a new folder for your plugin e.g., `hello_world_plugin`.

- Inside the "hello_world_plugin" directory, create: `hello_world_plugin.info.yml`:(This file contains information about your module.) 

``` yml
name: 'Hello World Plugin'
type: module
description: 'A simple block plugin that displays a greeting.'
core_version_requirement: ^8 || ^9
core_version: ^8 || ^9
package: Custom
dependencies:
  - drupal:block

``` 
and `hello_world_plugin.module` (This file contains PHP code for your module.)

``` php
<?php

/**
 * Implements hook_help().
 */
function hello_world_plugin_help($route_name, \Drupal\Core\Routing\RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.hello_world_plugin':
      return '<p>' . t('A simple block plugin that displays a greeting.') . '</p>';
  }
}

use Drupal\block\BlockBase;
use Drupal\block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'Hello World' block plugin.
 *
 * @Block(
 *   id = "hello_world",
 *   admin_label = @Translation("Hello World"),
 * )
 */
class HelloWorldBlock extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#markup' => $this->t('Hello, World!'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
  }
}

```

- Go to your Drupal admin panel to enable and install the module.

- Last step In `Structure `-> `Block layout`, find the `Hello World` block and place it in a region of your choice..

Now, when you visit your Drupal site, you should see a "Hello, World!" greeting displayed in the region where you placed the block. 

## WordPress

WordPress, initially a blogging tool, evolved into an open-source web content management system. Its plugin architecture allows users to extend website or blog functionality, focusing on hooks and filters.


WordPress plugin architecture allows users to extend functionality of a website or blog. Plugins in WordPress are built around the concept of **hooks and filters**. These are actions and functions that allow developers to modify and extend the core functionality of WordPress without altering its core code.


### Plugin definition

- 
A WordPress plugin typically needs one main file with a specifically formatted DocBlock in the header. At its simplest, a WordPress plugin is a **PHP file with a WordPress plugin header comment** 

- Plugins are loaded at runtime.

- **Hook based**:    
    - activation hook (run when you activate plugin)
    - deactivation hook (run when plugin is deactivated)
    - uninstall hook (run when plugin is deleted)
    - action hooks (add or change functionality) 
    - filter hooks (alert data) 

- Extension points are also hooks (You can add your own, custom hooks with `do_action()` , which will enable developers to extend your plugin)

- Rich API (DB, file, core API) 

### WordPress Hello World example

Follow these steps to create a "Hello World" plugin:

- Set Up Your Plugin Directory
    - Navigate to your WordPress installation's w`p-content/plugins` directory
    - Create a new directory for your plugin. You can name it something like "hello-world-plugin."

- Create Plugin
Create a PHP file with the same name as the directory and a .php extension. Here is the code 
``` php
<?php
/*
Plugin Name: Hello World Plugin
Description: A simple WordPress "Hello, World!" plugin.
Version: 1.0
Author: Your Name
*/

function hello_world() {
    echo "Hello, World!";
}

add_shortcode('hello-world', 'hello_world');

``` 

- Active plugin by log in in your admin panel in the plugins section click Active  

- Use plugin
where you want the plugin message to appear add the shortcode (`[hello-world]`).

## Visual Studio Code
Visual Studio Code (VS Code) is an extensible code editor enhanced through extensions or plugins.

From the authors: 

> Visual Studio Code is built with extensibility in mind. From the UI to the editing experience, almost every part of VS Code can be customized and enhanced through the Extension API. In fact, many core features of VS Code are built as extensions and use the same Extension API

### How Plugins in Visual Studio Code Work

- Each plugin has a `package.json` manifest file defining contributions through Contribution Points

- Plugins are implemented using JavaScript or TypeScript interacting with the VS Code API.

- Extensions are **lazy-loaded**, triggered by events or user actions (called **Activation Events**, such as opening a file).

- Extensions run in a separate process managed by the **Extension Host** component.

### Visual Studio Code Hello World example

- Set Up Your Development Environment by installing Yeoman and the VS **Code Extension Generator**

- In a new directory, run Yeoman to generate the extension scaffold. (Answer the prompts by selecting "New Extension (TypeScript)," providing a unique name, identifier, and a brief description. Choose "Yes" if you want to initialize a Git repository.):

```
yo code
```

- Implement the extension in the  in `src/extension.ts` file replace the existing code with the 
``` typescript
 
import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    const helloWorld = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right);
    helloWorld.text = "Hello, World!";
    helloWorld.show();
}

export function deactivate() {
    // This method is called when your extension is deactivated.
}

```

- Build and run the extension
``` cmd
npm install
code .
```

## Chrome extensions

Google Chrome extensions, or plugins, are small programs enhancing the Chrome browser's functionality

- The **`manifest.json`** file contains JSON describing the extension's capabilities and configuration.

- Chrome extensions are implemented using HTML, CSS, and JavaScript..

- Rich APIs include service workers, toolbar actions, and side panel APIs.

### Chrome extensions Hello World example

 
- Create a new folder for your extension (e.g., hello-world-extension).

- Inside the extension directory, create manifest.json and content.js (here goes extension code) files.

``` json
// manifest.json
{
  "manifest_version": 2,
  "name": "Hello World Extension",
  "version": "1.0",
  "description": "A simple Chrome extension that displays a hello world message on the current web page.",
  "permissions": [
    "activeTab"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

```


- `content.js`

``` js
alert('Hello, World! This is a Chrome extension without a popup.');
```

- Load the extension by going to chrome://extensions/, selecting developer mode, and loading unpacked

## Eclipse IDE

Eclipse is an extensible IDE built on the OSGi framework, providing a modular and dynamic component system.

### Overview of how plugins in Eclipse IDE are implemented

- Each Eclipse plugin has a `plugin.xml` manifest file containing metadata and declaring extensions and dependencies.

- functionality is added through the implementation of **extension points**. When a developer creates a plugin, they can contribute to existing extension points or define their extension points for others to extend. This enables modular and extensible development.

- Plugins have a lifecycle with activation and deactivation phases.

- Eclipse plugins can define new commands and handlers, leveraging a rich set of APIs.

- Plugins in Eclipse can use a **rich set of APIs** provided by the Eclipse platform. These APIs cover areas such as UI, resource management, team support, debugging, and more.

### Eclipse IDE plugin Hello World example

- nstall the Eclipse Plug-in Development Environment (PDE) and create a new plugin project (use the "Hello, World Command" template). 

- in `src` floder is class `HelloWorldHandler.java`

``` java
package helloworldplugin.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

public class HelloWorldHandler extends AbstractHandler {

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
        MessageDialog.openInformation(window.getShell(), "Hello World", "Hello, Eclipse World!");
        return null;
    }
}
```  

## Summary


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ld8xharkgztaldqw6cn.png)

Across these platforms implementation of plugin configuration, loading, running, hooks, extension points and communication varies but the goal is same: Give developers a seamless and adaptable framework for extending and customizing functionalities.

After exploring concrete implementations, in the next blog post, we will embark on creating our own plugin and framework. This step will allow us to apply the acquired knowledge firsthand, developing our own adaptable and functional system for extension and customization.