Principle and Example of Plug in Mechanism in PHP

  • 2021-07-07 06:51:03
  • OfStack

PHP project in a lot of plug-in place, more especially after the basic program written by the third party to improve the development of a lot of functions, more can use plug-in mechanism, now say 1 plug-in implementation. The feature is that no matter whether you activate it or not, it will not affect the operation of the main program, even if it is deleted.

From the perspective of one plug-in installation to running process, there are mainly three steps:

1. Plug-in installation (the process of collecting and memorizing plug-in information, such as putting it in a database or XML)

2. Plug-in activation (open the plug-in and let the place where you listen for the plug-in start calling)

3. Plug-in running (implementation of plug-in functions)

From the running of a plug-in, the main points are as follows:

1. Dynamic listening and loading of plug-ins (information acquisition of plug-ins)

2. Dynamic triggering of plug-ins (running of plug-ins)

A complete plug-in system mainly includes the following:

1. Plug-in installation and uninstallation

2. Plug-ins open and close

3. Plug-in information acquisition

4. Plug-in Scheduling (Plug-in Manager)

5. Plug-in body

The main implementation of the program is as follows:

1. Registration and initialization of plug-ins

2. Determine activation conditions

3. Hook activation

4. Run the plug-in

Example code:


<?php
/** 
* PluginManager Class 
* 
*  Implementation core class of plug-in mechanism  
* 
* @link https://www.ofstack.com/ 
*/ 
class PluginManager 
{ 
  /** 
   *  Listen for registered plug-ins  
   * 
   * @access private 
   * @var array 
   */ 
  private $_listeners = array(); 
   /** 
   *  Constructor  
   * 
   * @access public 
   * @return void 
   */ 
  public function __construct() 
  { 
    # Here $plugin The array contains information about the plug-ins that we retrieve have been activated by the user  
   # For the convenience of demonstration, we assume that $plugin Include at least  
   #$plugin = array( 
    #  'name' => ' Plug-in name ', 
    #  'directory'=>' Plug-in installation directory ' 
    #); 
   
 
   // $plugins = get_active_plugins();# Please implement this function by yourself  
 
    // The final data structure effect after the function is implemented is as follows 
    $plugins=array(array("directory"=>"demo",
    "name"=>"DEMO"));
 
 
    if($plugins) 
    { 
      foreach($plugins as $plugin) 
 
      {// Assume that each plug-in folder contains 1 A actions.php File, which is the concrete implementation of the plug-in  
        if (@file_exists(STPATH .'plugins/'.$plugin['directory'].'/actions.php')) 
        { 
          include_once(STPATH .'plugins/'.$plugin['directory'].'/actions.php'); 
          $class = $plugin['name'].'_actions'; 
          if (class_exists($class)) 
          { 
            // Initialize all plug-ins  
            //$this  Is a reference to this class 
            new $class($this); 
          } 
        } 
      } 
    } 
    # Do something about logging here  
  } 
 
  /** 
   *  Register plug-in methods (hooks) that need to be listened to  
   * 
   * @param string $hook 
   * @param object $reference 
   * @param string $method 
   */ 
  function register($hook, &$reference, $method) 
  { 
    // Gets the method to be implemented by the plug-in  
    $key = get_class($reference).'->'.$method; 
    // Add a reference to a plug-in along with a method push Enter the listening array  
    $this->_listeners[$hook][$key] = array(&$reference, $method); 
    # Do something about logging here  
  } 
  /** 
   *  Trigger 1 A hook  
   * 
   * @param string $hook  The name of the hook  
   * @param mixed $data  Entry of hook  
   *  @return mixed 
   */ 
  function trigger($hook, $data='') 
  { 
    $result = ''; 
    // Check whether the hook to be implemented is in the listening array  
    if (isset($this->_listeners[$hook]) && is_array($this->_listeners[$hook]) && count($this->_listeners[$hook]) > 0) 
    { 
      //  Loop call starts  
      foreach ($this->_listeners[$hook] as $listener) 
      { 
        //  Fetch the reference and method of plug-in object  
        $class =& $listener[0]; 
        $method = $listener[1]; 
        if(method_exists($class,$method)) 
        { 
          //  Methods of calling plug-ins dynamically  
          $result .= $class->$method($data); 
        } 
      } 
    } 
    # Do something about logging here  
    return $result; 
  } 
} 
 
define(STPATH, "./");
 
$pluginManager=new PluginManager();
 
$pluginManager->trigger("demo");

demo plug-in file:


<?php
/**
 *  This is 1 A Hello World Implementation of Simple Plug-in 
 *
 * @link    https://www.ofstack.com/
 */
/**
 * Several default rules to note: 
 *  1.  The file name of this plug-in class must be action
 *  2.  The name of the plug-in class must be { Plug-in name _actions}
 */
class DEMO_actions
{
  // The parameters of the analytic function are pluginManager Reference to 
  function __construct(&$pluginManager)
  {
    // Register this plug-in 
    // No. 1 1 The parameter is the name of the hook 
    // No. 1 2 The parameters are pluginManager Reference to 
    // No. 1 3 Is the method executed by the plug-in 
    $pluginManager->register('demo', $this, 'say_hello');
  }
 
  function say_hello()
  {
    echo 'Hello World';
  }
}

Related articles: