Object oriented programming in PHP: a revolution in WordPress development
8 mins read

Object oriented programming in PHP: a revolution in WordPress development

wp-oop-in-php

Object oriented programming (OOP) is an important paradigm in software, with the core being “objects” – class instances that include data and behavior rather than “actions”.

PHP, known for its server-side scripting, has benefited greatly from OOP. This is because OPP supports modular and reusable code, making it easier to maintain. Conversely, this is also beneficial for better organizing and expanding large-scale projects.

For developers who use WordPress themes, plugins, and custom solutions, mastering OOP is crucial. In this article, we will provide an overview of what OOP in PHP is and its impact on WordPress development. We will also guide you on how to implement OOP principles in PHP.

Prerequisite

To learn the practical part of this article, please ensure that you have the following qualifications:

  • XAMPP (or similar software) for Apache and MySQL
  • PHP environment with version 7.4 or higher
  • Code editor, such as Visual Studio Code
  • Local or network hosted WordPress installation.
  • Knowledge of PHP and WordPress

 

The advantages of OOP in PHP development

By enhancing modularity, reusability, scalability, maintainability, and teamwork, OOP greatly promotes the development of PHP. It organizes PHP code by dividing it into objects, each representing a specific part of the application. By using objects, you can easily reuse code, saving time and reducing errors.

Given this, let’s delve deeper into the two specific advantages of OOP in PHP, with a focus on how it changes the development process.

1. Code reuse and maintenance

Due to its inheritance and polymorphism, OOP in PHP makes code reuse simple and feasible. Classes can use properties and methods from other classes. In this way, with slight modifications, the old code can be used in a new way.

OOP can also make it easier for you to manage code. Encapsulation means that an object maintains its privacy of details, only shares the required content, and uses special methods called getters and setters. This method helps prevent changes in one part of the application from causing problems in other parts, making code updates and maintenance easier.

In addition, as the object itself is complete, it becomes easier to find and fix errors in certain parts of the system. This improves the overall quality and reliability of the code.

2. Enhance clarity and structure

Using classes and objects, OOP makes PHP code more concise and organized. A class is like a template for an object, putting together everything that belongs to the same place.

OOP also allows classes to use the functionality of other classes, which means you don’t have to write the same code repeatedly. All of these contribute to making the code simpler, easier to fix, and more organized.

The clear code brought by OOP helps teams work better together. Everyone is more likely to understand the purpose of the code, which means less time for interpretation and more time for work. It can also reduce errors and help projects get on track. When the code is neat and organized, new members in the team can also quickly keep up with the progress.

 

Implementing OOP in PHP

In PHP’s OOP, you use classes and objects to organize code, just like blueprints and houses. You can create classes for anything, such as users or books, including their features and actions. Then, use inheritance to create a new class from the existing class, so that the code is not duplicated and time is saved. Moreover, due to encapsulation, certain parts of the class remain private, making the code more secure.

The following chapters will teach you how to effectively use OOP principles in PHP programming. We have created a Content Management System (CMS) to manage articles.

1. Define a class with properties and methods

First, create an Article class that includes attributes for title, content, and status, as well as methods to set and display these attributes.

class Article {
private $title;
private $content;
private $status;
const STATUS_PUBLISHED = 'published';
const STATUS_DRAFT = 'draft';
public function __construct($title, $content) {
$this->title = $title;
$this->content = $content;
$this->status = self::STATUS_DRAFT;
}
public function setTitle($title) {
$this->title = $title;
return $this;
}
public function setContent($content) {
$this->content = $content;
return $this;
}
public function setStatus($status) {
$this->status = $status;
return $this;
}
public function display() {
echo "<h2>{$this->title}</h2><p>{$this->content}</p><strong>Status: {$this->status}</strong>";
}
}

2. Create objects and implement method chains

Create an article object and set its properties using method chains:

$article = new Article("OOP in PHP", "Object-Oriented Programming concepts.");
$article->setTitle("Advanced OOP in PHP")->setContent("Exploring advanced concepts in OOP.")->setStatus(Article::STATUS_PUBLISHED)->display();

3. Strengthen encapsulation and inheritance

Use getter and setter methods to enhance encapsulation and create a FeaturedArticle class that inherits from Article:

class FeaturedArticle extends Article {
private $highlightColor = '#FFFF00'; // Default highlight color
public function setHighlightColor($color) {
$this->highlightColor = $color;
return $this;
}
public function display() {
echo "<div> style='background-color: {$this->highlightColor};'>";
parent::display();
echo "</div>";
}
}
$featuredArticle = new FeaturedArticle("Featured Article", "This is a featured article.");
$featuredArticle->setStatus(FeaturedArticle::STATUS_PUBLISHED)->setHighlightColor('#FFA07A')->display();

4. Interface and polymorphism

Define an interface for publishable content and implement it in the Article class to demonstrate polymorphism:

interface Publishable {
public function publish();
}
class Article implements Publishable {
// Existing class code...
public function publish() {
$this->setStatus(self::STATUS_PUBLISHED);
echo "Article '{$this->title}' published.";
}
}
function publishContent(Publishable $content) {
$content->publish();
}
publishContent($article);

5. Use traits to achieve sharing behavior

PHP allows adding features to classes using traits without inheriting from other classes. Using the following code, introduce a feature for recording activities in CMS:

trait Logger {
public function log($message) {
// Log message to a file or database
echo "Log: $message";
}
}
class Article {
use Logger;
// Existing class code...
public function publish() {
$this->setStatus(self::STATUS_PUBLISHED);
$this->log("Article '{$this->title}' published.");
}
}

OOP in WordPress development

The OOP principle greatly enhances the development capabilities of WordPress, especially when creating themes, plugins, and widgets. With the help of OOP, you can write simpler, more scalable, and maintainable code for WordPress websites.

This section reviews how to apply OOP in WordPress development. We will provide some examples that you can copy and paste into your WordPress deployment for testing.

OOP in WordPress themes: custom article type registration

To demonstrate how to use OOP in WordPress themes, you need to create a class to handle the registration of custom article types.

Put the following code into the functions. PHP file of the theme. You can find your theme in the wp content/themes directory.

class CustomPostTypeRegistrar {
private $postType;
private $args;
public function __construct($postType, $args = []) {
$this->postType = $postType;
$this->args = $args;
add_action('init', array($this, 'registerPostType'));
}
public function registerPostType() {
register_post_type($this->postType, $this->args);
}
}
// Usage
$bookArgs = [
'public' => true,
'label'  => 'Books',
'supports' => ['title', 'editor', 'thumbnail'],
'has_archive' => true,
];
new CustomPostTypeRegistrar('book', $bookArgs);

This code dynamically registers a custom article type book, and its detailed information is passed through the bookArgs array. You can see the newly created custom article type, labeled Books, in the WordPress management sidebar.

Object oriented programming in PHP: a revolution in WordPress development

Books Custom Article Type Sidebar Element

This example illustrates how OOP encapsulates the ability to register custom article types, making them reusable for different types of articles.

OOP in WordPress plugin: Simplified code handler

In a plugin example, you need to develop a class to handle abbreviations used to display special information. You can add the following abbreviation to any article or page to test this feature.

<?php
/**
* Plugin Name: OOP Shortcode Handler
* Description: Handles a custom shortcode with OOP.
* Version: 1.0
* Author: Name
*/
class OOPShortcodeHandler {
public function __construct() {
add_shortcode('oop_message', array($this, 'displayCustomMessage'));
}
public function displayCustomMessage($atts) {
$attributes = shortcode_atts(['message' => 'Hello, this is your OOP     
message!'], $atts);
return "<div>{$attributes['message']}</div>";
}
}
new OOPShortcodeHandler();

Save it as my oop shortcode handler. php in the wp-content/plugins directory. Finally, activate the plugin.

Object oriented programming in PHP: a revolution in WordPress development

My OOP short code handler listed on the plugin page

Next, before publishing or updating, use the [oop_message] and [oop_message message="Custom Message Here"] The shortcut code is as follows:

 

Object oriented programming in PHP: a revolution in WordPress development

The example page in editing mode has added custom shortcut code information.

After publishing or updating the page/post, you will see the information displayed in simplified code.

 

Object oriented programming in PHP: a revolution in WordPress development

A sample page with custom abbreviation information that has been published.

OOP in WordPress Widgets: Dynamic Content Widget

OOP is also very beneficial for widgets by encapsulating the functionality of small tools in the class. The WordPress kernel itself uses OOP for small tools. Here, you can create a custom widget that allows users to display dynamic content through the title and text area.

Add the following code to the functionalis.php file or plugin of the theme. It defines a custom widget to display the “Hello World From My Custom Widget!” message.

class My_Custom_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'my_custom_widget', // Base ID
'My Custom Widget', // Name
array('description' => __('A simple custom widget.', 
'text_domain'),) // Args
);
}
public function widget($args, $instance) {
echo $args['before_widget'];
if (!empty($instance['title'])) {
echo $args['before_title'] . apply_filters('widget_title',  
$instance['title']) . $args['after_title'];
}
// Widget content
echo __('Hello World From My Custom Widget!', 'text_domain');
echo $args['after_widget'];
}
public function form($instance) {
// Form in WordPress admin
}
public function update($new_instance, $old_instance) {
// Processes widget options to be saved
}
}
function register_my_custom_widget() {
register_widget('My_Custom_Widget');
}
add_action('widgets_init', 'register_my_custom_widget');

When editing activity themes using custom links under the appearance of the management area, you can add new custom widgets as needed.

Object oriented programming in PHP: a revolution in WordPress development

Customize the widget settings on the sidebar and use the widgets on the sample page.

Using the WordPress class

WordPress offers various types that you can use to interact with the core features of content management systems. Two of these classes are WP_User and WP-Post, which represent users and articles, respectively.

Expand the WordPress plugin example from the previous section and create a simplified code that displays the author’s information and detailed information about the post itself by combining these classes.

Save it as my oop shortcode handler extended. php in the wp content/plugins directory. Finally, enable the plugin.

<?php
/**
* Plugin Name: Extended OOP Shortcode Handler
* Description: Extends the shortcode handler to display post and author 
information.
* Version: 1.1
* Author: Your Name
*/
class ExtendedOOPShortcodeHandler {
public function __construct() {
add_shortcode('post_author_details', array($this,   
'displayPostAuthorDetails'));
}
public function displayPostAuthorDetails($atts) {
global $post; // Accessing the global $post object to get current post  
details
$attributes = shortcode_atts([
'post_id' => $post->ID, // Default to the current post ID
], $atts);
$postDetails = get_post($attributes['post_id']); // Getting the WP_Post  
object
if (!$postDetails) {
return "Post not found.";
}
$authorDetails = new WP_User($postDetails->post_author); // Getting the 
WP_User object
$output = "<div class='post-author-details'>";
$output .= "<h2>Author Information</h2>";
$output .= "<p>Name: " . esc_html($authorDetails->display_name) . 
"</p>";
$output .= "<h2>Post Information</h2>";
$output .= "<p>Title: " . esc_html($postDetails->post_title) . "</p>";
$output .= "<p>Content: " . 
esc_html(wp_trim_words($postDetails->post_content, 20, '...')) . "</p>";
$output .= "</div>";
return $output;
}
}
new ExtendedOOPShortcodeHandler();

In this extended version, you have created a simplified code: [post_author_details post_id="1"]

 

Object oriented programming in PHP: a revolution in WordPress development

Added an example page in editing mode with extended custom QR code information.

When added to an article or page, it displays detailed information about the author of the article (using the WP_User class) and the article itself (using the WP_Post class).

OOP and WordPress REST API

The WordPress REST API is a new feature of WordPress that allows you to interact with website data in a more programmable way. It extensively utilizes OOP, using classes to define endpoints, responses, and request processing. This is clearly a shift from traditional program foundations to embracing OOP.

In sharp contrast to OOP principles, most of WordPress’s core content, especially its early components such as themes and plugin APIs, were written in a procedural programming style.

For example, programmatic methods may directly manipulate global variables and rely on a series of functions to complete tasks, while OOP in REST APIs encapsulates logic in classes. Therefore, specific methods in these classes can handle tasks such as getting, creating, updating, or deleting posts.

This clearly separates the focus, making the code base easier to extend and debug.

The REST API provides a structured and extensible way to interact with WordPress data and return JSON formatted responses by defining endpoints and processing request classes, such as obtaining articles through GET/wp json/wp/v2/posts requests.

Summary

As you can see in this article, OOP provides unparalleled flexibility, scalability, and maintainability for PHP and WordPress development.