Trong CodeIgniter 3 (CI3) bản chất không có cơ chế “plugin” và “on/off” sẵn như WordPress, nhưng ta có thể tự thiết kế một cơ chế gần tương tự.
Mình gợi ý hướng triển khai như sau:
Tạo riêng một thư mục application/plugins/
để chứa các plugin:
application/ ├── plugins/ │ ├── sample_plugin/ │ │ ├── Plugin.php │ │ └── config.php │ ├── another_plugin/ │ │ ├── Plugin.php │ │ └── config.php
Trong đó:
Plugin.php
chứa code xử lý (giống như functions.php
trong WP plugin).config.php
khai báo metadata: tên, mô tả, trạng thái on/off
.Ví dụ application/plugins/sample_plugin/config.php
:
<?php return [ 'name' => 'Sample Plugin', 'slug' => 'sample_plugin', 'description' => 'Plugin demo cho CI3', 'active' => true // bật/tắt ];
Ví dụ application/plugins/sample_plugin/Plugin.php
:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Sample_plugin { public function __construct() { // Code khởi tạo } public function run() { log_message('info', 'Sample_plugin is running!'); // Code xử lý chính của plugin } }
Tạo file application/libraries/Plugin_manager.php
:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Plugin_manager { protected $plugins_path; protected $plugins = []; public function __construct() { $this->plugins_path = APPPATH . 'plugins/'; $this->load_plugins(); } private function load_plugins() { foreach (glob($this->plugins_path . '*/config.php') as $config_file) { $config = include $config_file; if (!empty($config['active']) && $config['active'] === true) { $plugin_dir = basename(dirname($config_file)); $class_file = $this->plugins_path . $plugin_dir . '/Plugin.php'; if (file_exists($class_file)) { include_once $class_file; $class_name = ucfirst($plugin_dir); // Sample_plugin if (class_exists($class_name)) { $this->plugins[$plugin_dir] = new $class_name(); } } } } } public function run_all() { foreach ($this->plugins as $plugin) { if (method_exists($plugin, 'run')) { $plugin->run(); } } } public function get_plugins() { return $this->plugins; } }
Trong application/config/autoload.php
thêm vào libraries
:
$autoload['libraries'] = array('plugin_manager');
Trong controller nào đó:
public function index() { $this->plugin_manager->run_all(); }
config.php
của plugin ('active' => true/false
).ci_plugins
) để bật/tắt plugin thông qua admin panel.