Here is an example of how you can create a WordPress plugin using the Model-View-Controller (MVC) structure in PHP 8:
- Create a new folder in the
wp-content/plugins
directory and name itmy-plugin
. - Inside the
my-plugin
folder, create the following subfolders:controller
,model
, andview
. - In the
controller
folder, create a new file calledMyPluginController.php
and add the following code:
class MyPluginController { public function __construct() { // Initialize the plugin } public function handleRequest() { // Handle the request and call the appropriate model and view methods } }
- In the
model
folder, create a new file calledMyPluginModel.php
and add the following code:
class MyPluginModel { public function getData() { // Retrieve data from the database or external API } public function saveData($data) { // Save data to the database } }
- In the
view
folder, create a new file calledMyPluginView.php
and add the following code:
class MyPluginView { public function render($data) { // Render the data to the screen } }
- In the
my-plugin
folder, create a new file calledmy-plugin.php
and add the following code:
<?php /* Plugin Name: My Plugin */ require_once __DIR__ . '/controller/MyPluginController.php'; require_once __DIR__ . '/model/MyPluginModel.php'; require_once __DIR__ . '/view/MyPluginView.php'; $controller = new MyPluginController(); $controller->handleRequest();
- Activate the plugin in the WordPress admin panel and you should see your plugin working.
This is a basic example of how you can structure a WordPress plugin using the MVC pattern in PHP 8. You can further customize the plugin by adding more functionality and features to the controller, model, and view classes.