WordPress Plugin Development: Basics OOP Concepts

WordPress Plugin Development: Basics OOP Concepts
WordPress Plugin Development: Basics OOP Concepts

Today, we will learn some basics OOP Concepts on our WordPress Plugin Development series. Our first WordPress Development blog post was just an introduction where we created a simple “Hello World Plugin” to output a text on the client side.

WordPress Plugin Development: Getting Started

We will start by implementing restriction on our plugin for security reasons and discuss Object Oriented Programming on WordPress Plugin Development.

If you have followed the tutorial from the previous blog post, you must have created the “Hello World Plugin” so open it on your editor and let’s start coding.

If you remember, we talk about why our plugin is not secure. I think talking about security before creating our plugin might not be a great start to the series but I want to keep things straight. We will write secure code on the first place and then refactor later if we missed any.

So, currently the issue with our plugin is anyone can access our plugin files and if your plugin does something with the parameters passed on URL or does some I / O stuff, user can execute a function or run a malicious script using PHP file. So, we block direct access.

In your hello-world.php file, lets block the direct access to our file.

<?php
/**
*
* @package hello-world
*
* Plugin Name: Hello World
* Plugin URI: https://www.ashiish.me/
* Description: A plugin to greet the visitors or just another test plugin to be honest.
* Version: 1.0.0
* Author: Ashish Yadav
* Author URI: https://www.ashiish.me/
* License: GPLv2 or later
* Text Domain: hello-world
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*
*/
if(!defined('ABSPATH')) {
die; // Die if accessed directly.
}
view raw hello-world.php hosted with ❤ by GitHub

Now, the above code will check if the ABSPATH is defined or not. If not, we exit the further execution using die.

If you had tried to access the plugin file before, you might have found some PHP Errors. You can try to access the file now and it does nothing.

We still have another problem, our plugin directory is listing PHP Files. It can be solved very easily, add an empty index.php file which will be executed by default.

<?php
/*
* an empty file or use a header function to redirect to the root url.
* @redirect: header('Location: https://yoursite.com');
*
*/
?>
view raw index.php hosted with ❤ by GitHub

Now we are done with some important parts. Let’s learn some Object Oriented Programming Concepts.

I assume that you already understand the OOP concept. We will use basics OOP on plugin development.

If you are new to object-oriented programming, I would like to keep it very simple and limited. I will not explain in depth. There will be a few examples. If you want to know more about OOP, you can refer to any complete OOP tutorials.

Check: Object-Oriented Programming

Object-Oriented Programming

A simple introduction can be to represent data or methods using objects which can be reused multiple times, can be inherited and makes the task easier.

In OOP, the class is used as a blueprint of an object to define data and methods. Once a class is defined, we need to instantiate it.

<?php
// Class in php
class MyClass {
// our data and methods goes here
}
?>
view raw oop-example.php hosted with ❤ by GitHub

When you instantiate a class or object, it calls a method of our class known as constructor which initializes our object.

The constructor is the magical method which is automatically called when you instantiate. After the instantiation, the object variable allows us to access all our data and methods inside the class.

<?php
// Class in php
class MyClass {
// MyClass Constructor
function __construct() {
// empty
}
// our dummy method
function dummy_method() {
echo "Hello, World";
}
}
// Object instantiation
$myclass = new MyClass();
// now we can access the method inside our class.
$myclass->dummy_method(); // output: Hello, World
?>
view raw oop-example.php hosted with ❤ by GitHub

In the above code, we have created our class with a constructor and a method. We instantiate our class and access the method dummy_method.

In OOP, when we are working with an instance of the object. The reference is very important. We use $this a lot of time in our WordPress plugin development which has a reference to the current object.

There are four principles of OOP but we will talk about only two.
– Encapsulation
– Inheritance

Encapsulation

Encapsulation works by binding the private state with public methods. It’s like keeping things private inside the class which cannot be called or modified publicly but only accessible using the public method provided to access or modify the private state.

It gives a full control to our data.

<?php
// Class in php
class MyClass {
// our private variable
private $name;
// MyClass Constructor
function __construct() {
// empty
}
// our public method to return $name
public function getName() {
// $this refers to the current object
return $this->name;
}
// our public method to modify $name
public function setName($string) {
//$this refers to the current object
$this->name = $string;
}
}
// Object instantiation
$myclass = new MyClass(); //
/*
* now we can access the method inside our class.
* We have encapsulated our $name variable.
*/
$myclass->setName("Ashish"); // sets the string value Ashish
$myclass->getName(); // OUTPUT: Ashish
// We cannot directly assign a value to our $name variable. Generates Error.
$myclass->name = "Ashish"; // Is not valid. We are not allowed to modified
?>

Inheritance

Inheritance is about sharing the same behavior with different classes. You can even take an example from Biology about the genetic transmission of characteristics from parent to offsprings.

<?php
// Class in php
class Parents {
public function eye_color() {
echo "Black";
}
}
class Children extends Parents {
// empty
}
$parents = new Parents();
$children = new Children();
$parents->eye_color(); // OUTPUT: Black
/*
* We use extends keyword to inherit methods and properties from Parents class
* Our Parents class has an method eye_color which is public
* and accesible by our Children class
* We instantiate our both classes and prints the eye_color
* We inherit our Parents eye color "Black".
*/
$children->eye_color(); // OUTPUT: Black
?>
view raw inheritance.php hosted with ❤ by GitHub

You might wonder why use Object Oriented Programming where WordPress is not built on OOP Principles.

The first reason is, objects helps us to organize our code. We can reuse them, share them, limit access to our data.

WordPress Plugin can grow very large according to the requirements. Things get confusing and complicated. So, it helps to reduce the complexity and help us to organize our plugin more.

There are other reasons too like it does helps us in easy debugging but one of another important reason is to avoid conflicts between plugins. This might sound weird.

Just make a guess about how many plugins are there in the WordPress Plugin directory? I guess millions. Many WordPress websites depend on plugins.

If there is a conflict between plugins name, or with core functions of WordPress. It will create an error or our site will fail to load the plugin.

WordPress was built in a procedural way. Back in those days, PHP didn’t have OOP support. We can create plugins on procedural way too. We did the same thing in our hello world plugin in the previous tutorial. We created a simple function to output a string. The same function name can be used by another plugin and it might conflict.

One way to fix conflict on procedural programming paradigm is to use a unique prefix on our every function and check if the function doesn't exists.

<?php
/**
*
* @package hello-world
*
* Plugin Name: Hello World
* Plugin URI: https://www.ashiish.me/
* Description: A plugin to greet the visitors or just another test plugin to be honest.
* Version: 1.0.0
* Author: Ashish Yadav
* Author URI: https://www.ashiish.me/
* License: GPLv2 or later
* Text Domain: hello-world
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*
*/
if(!defined('ABSPATH')) {
die; // Die if accessed directly.
}
// Procedural programming or the WordPress way
/*
* Prefix: hello_world
* Procedural way
*/
if(!function_exists('hello_world_greet')) {
function hello_world_greet() {
// do something
}
}
if(!function_exists('hello_world_add_something')) {
function hello_world_add_something() {
// do something
}
}
if(!function_exists('hello_world_delete_something')) {
function hello_world_delete_something() {
// do something
}
}
view raw hello-world.php hosted with ❤ by GitHub

I just want to show why we should use OOP. See the code, every time we need to define a function to do something, we need to check if it already exists on the core or in the list of function defined by themes or plugins.

Lots of writing and checking and will grow more if our plugin grows.

We can use OOP Concepts and add a unique prefix to our class name. Any methods or function inside our class will need an instance of the class. We can name our methods or function with any name. We can use access modifiers to control or restrict access. It reduces complexity and makes our task easier.

Below is an example of class based Hello World Plugin.

<?php
/**
*
* @package hello-world
*
* Plugin Name: Hello World
* Plugin URI: https://www.ashiish.me/
* Description: A plugin to greet the visitors or just another test plugin to be honest.
* Version: 1.0.0
* Author: Ashish Yadav
* Author URI: https://www.ashiish.me/
* License: GPLv2 or later
* Text Domain: hello-world
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*
*/
if(!defined('ABSPATH')) {
die; // Die if accessed directly.
}
/**
* HelloWorld Class
*
* @class HelloWorld
*/
class HelloWorld_Plugin {
// our methods or functions here
}
// check if our class exists
if(class_exists('HelloWorld_Plugin')) {
// instantiate the class.
$hellWorld_plugin = new HelloWorld_Plugin();
}
view raw hello-world.php hosted with ❤ by GitHub

Now, we can implement our old function inside our class to print some text like before. Below is a complete plugin using PHP classes that output some text on our website.

<?php
/**
*
* @package hello-world
*
* Plugin Name: Hello World
* Plugin URI: https://www.ashiish.me/
* Description: A plugin to greet the visitors or just another test plugin to be honest.
* Version: 1.0.0
* Author: Ashish Yadav
* Author URI: https://www.ashiish.me/
* License: GPLv2 or later
* Text Domain: hello-world
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*
*/
if(!defined('ABSPATH')) {
die; // Die if accessed directly.
}
/**
* HelloWorld_Plugin Class
*
* @class HelloWorld_Plugin
*/
class HelloWorld_Plugin {
/*
* Consructors are magical functions
* They are executed when you instantiate a object.
* It initializes our object.
* Call your function inside Consrtuctor to execute immediately.
* Use $this for the reference of an object
*/
function __construct() {
// executes our congratulations function.
$this->congratulations();
}
// Congratulations function
function congratulations() {
echo "Congratulations, you have just learned basics OOP and Plugin Development using Object Oriented Programming.";
}
}
// check if our class exists
if(class_exists('HelloWorld_Plugin')) {
// instantiate the class.
$hellWorld_plugin = new HelloWorld_Plugin();
}
view raw hello-world.php hosted with ❤ by GitHub

In our next tutorial, we will start our new plugin that will be based on above examples and we will implement it in a better way. A simple working plugin that can be used for production as well. Thank you for your time.

If you have any doubts or questions feel free to comment below.