PHP code example of webmoves / plugin-base

1. Go to this page and download the library: Download webmoves/plugin-base library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

webmoves / plugin-base example snippets


// Get a configuration value
$apiKey = $this->core->get_config()->get('api.key', 'default_key');

// Check if a configuration value exists
if ($this->core->get_config()->has('feature.enabled')) {
    // Do something
}

// Set a configuration value at runtime
$this->core->get_config()->set('cache.ttl', 3600);

use WebMoves\PluginBase\Contracts\Components\Component;
use WebMoves\PluginBase\Enums\Lifecycle;

class MyComponent implements Component
{
    public function register(): void
    {
        // Register hooks, filters, or other initialization code
        add_action('init', [$this, 'initialize']);
        add_filter('the_content', [$this, 'modify_content']);
    }
    
    public function can_register(): bool
    {
        // Only register this component in the admin area
        return is_admin();
    }
    
    public function get_priority(): int
    {
        // Standard priority
        return 10;
    }
    
    public function register_on(): Lifecycle
    {
        // Register on the INIT lifecycle
        return Lifecycle::INIT;
    }
   
    public function modify_content(string $content): string
    {
        // Modify the content
        return $content . '<p>Modified by MyComponent</p>';
    }
}

use WebMoves\PluginBase\Contracts\Components\Component;
use WebMoves\PluginBase\Concerns\Components\ComponentRegistration;
use WebMoves\PluginBase\Concerns\Components\HasAction;
use WebMoves\PluginBase\Concerns\Components\HasShortcode;
use WebMoves\PluginBase\Concerns\Components\HasFilter;
use WebMoves\PluginBase\Enums\Lifecycle;

class NoticeMessage implements Component {

    // Use the ComponentRegistration trait to implement the register() method automatically
    use ComponentRegistration;
    
    // Use capability traits for different WordPress functionalities
    use HasAction;
    use HasShortcode;
    use HasFilter;
    
    public function __construct(
        private string $notice_type = 'info', 
        private string $notice_message = '', 
        private bool $is_dismissible = true,
        private string $admin_notice_hook = 'admin_notices',
        private array $shortcode_defaults = ['type' => 'info', 'dismissible' => 'true']
    ) {
        // Constructor property promotion automatically assigns parameters to properties
    }
    
    /**
     * Define which lifecycle event this component should register on
     * Required by Component interface
     */
    public function register_on(): Lifecycle
    {
        return Lifecycle::ADMIN_INIT;
    }
    
    /**
     * Define the action hook to use
     * Required by HasAction trait
     */
    protected function get_action_hook(): string {
        return $this->admin_notice_hook;
    }
    
    /**
     * Define the filter hook to use
     * Required by HasFilter trait
     */
    protected function get_filter_hook(): string {
        return 'the_content';
    }
    
    /**
     * Define the shortcode tag to use
     * Required by HasShortcode trait
     */
    protected function get_shortcode_tag(): string {
        return 'notice';
    }
    
    /**
     * Hook that runs after trait registration is complete
     * This is provided by the ComponentRegistration trait
     */
    protected function after_register(): void {
        // Register additional hooks that aren't covered by the traits
        add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
    }
    
    /**
     * Implement the action functionality - display admin notice
     * Required by HasAction trait
     */
    public function execute_action(...$args): void {
        $dismissible_class = $this->is_dismissible ? ' is-dismissible' : '';
        echo '<div class="notice notice-' . esc_attr($this->notice_type) . $dismissible_class . '">';
        echo '<p>' . wp_kses_post($this->notice_message) . '</p>';
        echo '</div>';
    }
    
    /**
     * Implement the filter functionality - add notice to content
     * Required by HasFilter trait
     */
    public function execute_filter(...$args): mixed {
        $content = $args[0] ?? '';
        
        // Only add the notice to the main content, not excerpts or other filtered content
        if (!is_singular() || !in_the_loop() || !is_main_query()) {
            return $content;
        }
        
        $notice_html = '<div class="content-notice content-notice-' . esc_attr($this->notice_type) . '">';
        $notice_html .= '<p>' . wp_kses_post($this->notice_message) . '</p>';
        $notice_html .= '</div>';
        
        // Add notice at the beginning of the content
        return $notice_html . $content;
    }
    
    /**
     * Implement the shortcode rendering
     * Required by HasShortcode trait
     */
    protected function render_shortcode($atts, $content = null): string {
        // Parse attributes with defaults
        $attributes = shortcode_atts($this->shortcode_defaults, $atts);
        
        // Get type and dismissible from attributes
        $type = $attributes['type'];
        $dismissible = filter_var($attributes['dismissible'], FILTER_VALIDATE_BOOLEAN);
        
        // Build the shortcode output
        $output = '<div class="shortcode-notice shortcode-notice-' . esc_attr($type);
        $output .= $dismissible ? ' is-dismissible' : '';
        $output .= '">';
        
        if ($content) {
            $output .= '<p>' . do_shortcode($content) . '</p>';
        } else {
            $output .= '<p>' . wp_kses_post($this->notice_message) . '</p>';
        }
        
        $output .= '</div>';
        return $output;
    }
    
    /**
     * Custom method for enqueueing scripts and styles
     * Not 

// In your plugin's get_services() method
public function get_services(): array
{
    return [
        // Info notice for all users
        'info.notice' => new NoticeMessage(
            'info',                                          // Notice type
            'Welcome to our plugin! Check out the new features.', // Notice message
            true,                                            // Is dismissible
            'admin_notices'                                  // Admin hook
        ),
        
        // Warning notice only for admin users
        'warning.notice' => new NoticeMessage(
            'warning',                                       // Different notice type
            'Your license will expire in 7 days. Please renew.', // Different message
            false,                                           // Not dismissible
            'admin_notices',                                 // Same admin hook
            ['type' => 'warning', 'dismissible' => 'false']  // Different shortcode defaults
        ),
        
        // Error notice for network admin
        'error.notice' => new NoticeMessage(
            'error',                                         // Different notice type
            'Critical update 

  // Example plugin.config.php
  return [
      /*
      |--------------------------------------------------------------------------
      | Plugin Dependencies
      |--------------------------------------------------------------------------
      |
      | Define the list of plugins that must be installed and activated
      | for the plugin to function properly.
      |
      */
      'dependencies' => [
          'lients, etc.
      | These are registered in the container but don't implement Component.
      |
      */
      'services' => [
          DatabaseManager::class => create(DefaultDatabaseManager::class)
              ->constructor(
                  get(PluginCore::class),
                  get(Configuration::class)
              ),
          
          SettingsManagerFactory::class => create(DefaultSettingsManagerFactory::class)
              ->constructor(get(PluginMetadata::class)),
          
          TemplateRenderer::class => create(DefaultTemplateRenderer::class)
              ->constructor(get(PluginCore::class)),
          
          // Logger Factory
          LoggerFactory::class => create(LoggerFactory::class)
              ->constructor(get(Configuration::class), get('plugin.name')),
          
          // Default logger
          LoggerInterface::class => factory(function($container){
              return $container->get(LoggerFactory::class)->create('default');
          }),
      ],

      /*
      |--------------------------------------------------------------------------
      | Components
      |--------------------------------------------------------------------------
      |
      | Components that implement Component and will be registered
      | with the DefaultComponentManager for lifecycle management.
      |
      */
      'components' => [
          DependencyManager::class => create(DependencyManager::class)
              ->constructor(get(PluginCore::class)),
          
          DependencyNotice::class => create(DependencyNotice::class)
              ->constructor(get(DependencyManager::class)),
          
          DatabaseInstaller::class => create(DatabaseInstaller::class)
              ->constructor(get(DatabaseManager::class), get(LoggerInterface::class)),
      ],

      /*
      |--------------------------------------------------------------------------
      | Logging Configuration
      |--------------------------------------------------------------------------
      */
      'logging' => [
          'channels' => [
              'default' => [
                  'handlers' => ['stream', 'error_log'],
                  'processors' => [],
              ],
              'app' => [
                  'handlers' => ['stream'],
                  'processors' => [],
              ],
          ],
          'handlers' => [
              'stream' => [
                  'class' => StreamHandler::class,
                  'constructor' => [
                      'stream' => WP_CONTENT_DIR . '/debug.log',
                      'level' => Level::Debug,
                  ],
                  'formatter' => 'line',
              ],
              'error_log' => [
                  'class' => ErrorLogHandler::class,
                  'constructor' => [
                      'messageType' => ErrorLogHandler::OPERATING_SYSTEM,
                      'level' => Level::Error,
                  ],
                  'formatter' => 'line',
              ],
          ],
          'formatters' => [
              'line' => [
                  'class' => LineFormatter::class,
                  'constructor' => [
                      'format' => "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n",
                      'dateFormat' => 'Y-m-d H:i:s',
                  ],
              ],
          ],
      ],

      /*
      |--------------------------------------------------------------------------
      | Database Configuration
      |--------------------------------------------------------------------------
      */
      'database' => [
          'version' => '1.0.1',
          'delete_tables_on_uninstall' => true,
          'delete_options_on_uninstall' => true,
          'tables' => [
              'plugin_settings' => "CREATE TABLE {table_name} (
                  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
                  setting_key varchar(191) NOT NULL,
                  setting_value longtext,
                  setting_group varchar(100) DEFAULT 'general',
                  is_autoload tinyint(1) DEFAULT 0,
                  created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
                  updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                  PRIMARY KEY (id),
                  UNIQUE KEY idx_setting_key_group (setting_key, setting_group),
                  KEY idx_setting_group (setting_group),
                  KEY idx_autoload (is_autoload)
              ) {charset_collate};"
          ]
      ],

      /*
      |--------------------------------------------------------------------------
      | Asset Configuration
      |--------------------------------------------------------------------------
      */
      'assets' => [
          'version_strategy' => 'file_time', // 'file_time', 'plugin_version', 'manual'
          'minify_in_production' => true,
          'combine_css' => false,
          'combine_js' => false,
      ],
  ];
  

// Get a configuration value
$apiKey = $this->core->get_config()->get('api.key', 'default_key');

// Check if a configuration value exists
if ($this->core->get_config()->has('feature.enabled')) {
    // Do something
}

// Set a configuration value at runtime
$this->core->get_config()->set('cache.ttl', 3600);


/**
 * Plugin Name: Your Plugin
 * Plugin URI: https://example.com
 * Description: Your plugin description
 * Version: 1.0.0
 * Author: Your Name
 * Author URI: https://example.com
 * Text Domain: your-plugin
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Load Composer autoloader



namespace YourNamespace;

use WebMoves\PluginBase\PluginBase;
use WebMoves\PluginBase\Settings\MenuAdminPage;
use WebMoves\PluginBase\Pages\AbstractSettingsPage;
use WebMoves\PluginBase\Settings\DefaultSettingsBuilder;

class YourPlugin extends PluginBase
{
    public function initialize(): void
    {
        // Initialize your plugin
        $logger = $this->core->get_logger('app');
        $logger->info('Plugin initialized');
    }
    
    public function get_services(): array
    {
        $plugin_slug = 'your-plugin';
        
        // Create a settings builder with providers
        $builder = new DefaultSettingsBuilder(
            $this->get_core(),
            'your_plugin_settings',
            'your-plugin-settings',
            [
                new YourSettingsProvider('your-scope')
            ]
        );
        
        return [
            // Main plugin page
            MenuAdminPage::class => new MenuAdminPage($plugin_slug, 'Your Plugin', 'Your Plugin'),
            
            // Settings page as submenu
            AbstractSettingsPage::class => new AbstractSettingsPage(
                $builder,
                'Your Plugin Settings',
                'Settings',
                $plugin_slug
            ),
            
            // Other services
            YourService::class => new YourService(),
        ];
    }
}

public function get_services(): array
{
    return [
        MyService::class => new MyService(),
        'my-service' => function() {
            return new MyService();
        },
    ];
}

// config/plugin.config.php
return [
    'services' => [
        MyService::class => function() {
            return new MyService();
        },
    ],
];

$this->core->set('my-service', new MyService());

use WebMoves\PluginBase\Contracts\Settings\SettingsProvider;
use WebMoves\PluginBase\Settings\AbstractSettingsProvider;

class ApiSettingsProvider extends AbstractSettingsProvider
{
    public function get_settings_configuration(): array
    {
        return [
            'section' => [
                'id' => 'api_settings',
                'title' => __('API Settings', 'my-plugin'),
                'description' => __('Configure API connection settings.', 'my-plugin'),
            ],
            'fields' => [
                'api_key' => [
                    'label' => __('API Key', 'my-plugin'),
                    'type' => 'text',
                    'description' => __('Enter your API key.', 'my-plugin'),
                    'default' => '',
                    '

use WebMoves\PluginBase\Settings\MenuAdminPage;

// In your plugin's get_services() method
public function get_services(): array
{
    $plugin_slug = 'my-plugin';
    return [
        MenuAdminPage::class => new MenuAdminPage(
            $plugin_slug,           // Menu slug
            'My Plugin',            // Page title
            'My Plugin'             // Menu title
        ),
    ];
}

new MenuAdminPage(
    'my-plugin',                    // Menu slug
    'My Plugin',                    // Page title
    'My Plugin',                    // Menu title
    null,                           // Parent slug (null for top-level)
    'dashicons-admin-tools',        // Menu icon
    30                              // Menu position
);

use WebMoves\PluginBase\Pages\AbstractSettingsPage;
use WebMoves\PluginBase\Settings\DefaultSettingsBuilder;

// In your plugin's get_services() method
public function get_services(): array
{
    $plugin_slug = 'my-plugin';
    
    // Create a settings builder with providers
    $builder = new DefaultSettingsBuilder(
        $this->get_core(),
        'my_plugin_settings',      // Option name
        'my-plugin-settings',      // Page slug
        [
            new MySettingsProvider('my-scope'),
            new AnotherSettingsProvider('another-scope')
        ]
    );
    
    return [
        // Main plugin page
        MenuAdminPage::class => new MenuAdminPage($plugin_slug, 'My Plugin', 'My Plugin'),
        
        // Settings page as submenu
        AbstractSettingsPage::class => new AbstractSettingsPage(
            $builder,                  // Settings builder
            'My Plugin Settings',      // Page title
            'Settings',                // Menu title
            $plugin_slug               // Parent slug (for submenu)
        ),
    ];
}

use WebMoves\PluginBase\Pages\AbstractAdminPage;

class MyCustomPage extends AbstractAdminPage
{
    protected function render_admin_page(): void
    {
        // Render your custom page content
        echo '<div class="wrap">';
        echo '<h1>' . esc_html($this->get_page_title()) . '</h1>';
        echo '<p>This is my custom admin page.</p>';
        
        // Add your custom content, forms, tables, etc.
        
        echo '</div>';
    }
}

// In your plugin's get_services() method
public function get_services(): array
{
    $plugin_slug = 'my-plugin';
    return [
        // Main plugin page
        MenuAdminPage::class => new MenuAdminPage($plugin_slug, 'My Plugin', 'My Plugin'),
        
        // Custom page as submenu
        MyCustomPage::class => new MyCustomPage(
            'my-custom-page',      // Page slug
            'My Custom Page',      // Page title
            'Custom Page',         // Menu title
            $plugin_slug           // Parent slug (for submenu)
        ),
    ];
}

/config
  /plugin.config.php       # Main configuration file