Object-Oriented PHP for WordPress: Class Inheritance & Asynchronous, Lecture notes of Object Oriented Programming

This eBook provides an in-depth exploration of Object-Oriented PHP in WordPress development, covering topics such as class inheritance, asynchronous PHP, REST APIs, and more. Learn how to write efficient, reusable code and improve your WordPress development skills.

Typology: Lecture notes

2021/2022

Uploaded on 09/27/2022

mdbovary
mdbovary 🇬🇧

4.8

(8)

215 documents

1 / 103

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
THE ULTIMATE GUIDE
TO OBJECT-ORIENTED
PHP FOR WORDPRESS
DEVELOPERS
LEVELING UP AS WORDPRESS DEVELOPER WITH OBJECT-ORIENTED PHP
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Object-Oriented PHP for WordPress: Class Inheritance & Asynchronous and more Lecture notes Object Oriented Programming in PDF only on Docsity!

THE ULTIMATE GUIDE

TO OBJECT-ORIENTED

PHP FOR WORDPRESS

DEVELOPERS

LEVELING UP AS WORDPRESS DEVELOPER WITH OBJECT-ORIENTED PHP

WHAT’S INSIDE

  • INTRODUCTION
    • PHP IN A REST API WORLD
  • PHP 7 — GUEST CHAPTER BY TOM EWER
    • HOW PHP TOOK OVER THE WEB
    • PHP 7 FINALLY HEAVES INTO VIEW
    • WORDPRESS IS ABOUT TO GET WINGS
    • THERE ARE TWO KEY POINTS TO EMPHASIZE HERE
    • WHY DEVELOPERS ARE HOLDING FIRE ON SWITCHING
    • ARE YOU GOING TO USE PHP 7 IN PRODUCTION?
    • WHAT’S NEXT?
  • PHP FUNDAMENTALS
    • VARIABLES AND CONSTANTS
    • DATA TYPES
    • FUNCTIONS AND SCOPE
  • OBJECT-ORIENTED PHP
    • BEFORE WE BEGIN
    • METHODS VS. FUNCTIONS
    • PROPERTIES VS. VARIABLES
    • USING HOOKS IN CLASSES
    • MORE FUN WITH __CONSTRUCT()
  • WP_QUERY: THE OBJECT-ORIENTED PHP
    • A LITTLE BACKGROUND
    • WP_QUERY
    • MAKING YOUR OWN
    • WORDPRESS AS A GATEWAY TO OBJECT-ORIENTED
  • VISIBILITY IN OBJECT-ORIENTED PHP
    • ENCAPSULATION AND SCOPE
    • CLASSES VS. OBJECTS
    • THE THREE LEVELS OF VISIBILITY
    • RULES OF PROPERTY VISIBILITY
    • RULES OF METHOD VISIBILITY
    • WHY VISIBILITY MATTERS
    • A FEW LAST WORDS
  • CLASS INHERITANCE IN OBJECT-ORIENTED PHP
    • CLASS INHERITANCE
    • EXTENDING CLASSES AND OVERRIDING
    • ABSTRACT CLASSES
    • LESS CODE, BETTER CODE
  • HOW TO USE ASYNCHRONOUS PHP IN WORDPRESS
    • HOW IT WORKS
    • THE PROBLEM: ALL AT ONCE OR NOTHING
    • SETTING IT UP
    • WIRING IT UP
    • MORE ASYNCHRONOUS
  • REST APIS AND PHP
    • DESIGNING THE SYSTEM
    • PUTTING IT TOGETHER
    • STARTING IT UP
    • STARTING WITH A SYSTEM
  • PHP MAGIC METHODS
    • CONSTRUCTOR
    • SETTING HOOKS IN THE CONSTRUCTOR
    • MAGIC SETTERS AND GETTERS
    • CONVERTING OBJECTS TO STRINGS
    • USE MAGIC, LEARN MORE MAGIC
  • NAMESPACES
    • NAMESPACING YOUR CLASS
    • NESTING NAMESPACES
    • ALIASING NAMESPACES
    • NAMESPACE ALL THE THINGS!!!
  • IMPROVING DEVELOPMENT WORKFLOW WITH COMPOSER
    • WHEN AND WHERE TO USE COMPOSER
    • INSTALLING COMPOSER
    • WRITING A COMPOSER FILE
    • WAVING THE BATON
  • USING A CLASS AUTOLOADER TO IMPROVE WORDPRESS DEVELOPMENT
    • WHAT IS A CLASS AUTOLOADER?
    • CHOOSING A STANDARD
    • NOT CHOOSING A STANDARD
    • USING THE COMPOSER AUTOLOADER
    • USING A PSR-4 AUTOLOADER
    • THAT’S ALL IT TAKES
  • PHP DESIGN PATTERNS FOR WORDPRESS DEVELOPERS
    • EVENT DRIVEN VS. MODEL VIEW CONTROLLER
    • USEFUL PHP DESIGN PATTERNS
    • THE SINGLETON
    • WORDPRESS CORE GLOBALS
    • WHY?
  • IT’S TIME TO LEVEL UP YOUR PHP SKILLS
    • READ MORE SOURCE
    • MISUSED PATTERNS
    • COMPOSER AND CROSS-POLLINATION
    • YOUR TURN
  • CONCLUSION

INTRODUCTION

There are a lot of reasons why WordPress is so popular, but one is by far the flexibility and ease of use of the two languages it is written in: PHP and JavaScript. Both languages have a fairly low barrier to entry. But, while it is easy to get started, that does not mean it is always easy to learn. More advanced skills are required to create performant, maintainable, reusable and testable code. The first step in leveling up your skills as a developer is learning object-oriented programming for PHP or OOP. OOP is about more than using classes in your code. It’s about creating code that is less focused on a specific action and more focused on objects — small, reusable containers for data and functionality. PHP is the most popular programming language in the world — powering 84 percent of all websites. The server-side scripting language is known for its ability to create dynamic websites and for its use as a general-purpose programming language. PHP is open source, which combined with its ubiquity and capabilities, make it a perfect match for WordPress, the CMS that now powers more than 25 percent of the internet. Although WordPress users don’t need to learn PHP to manage their WordPress-powered websites, if you’re a plugin or theme developer, or just want to modify the default behavior of your site, you will need to have a basic understanding of PHP.

There are two types of PHP:

OO PHP vs. Procedural.

This ebook will equip you with the knowledge and skills you need to get started with object- oriented PHP as a WordPress developer, including:

  • PHP Fundamentals
  • Visibility and inheritance
  • PHP 7
  • WP_Query
  • Magic methods And more
PHP IN A REST API WORLD

In the era of the API-driven JavaScript interface, becoming the norm for WordPress development, PHP is more important than ever for WordPress users. This may sound strange, but all of these cool interfaces require a well built server-side application to power that application. That server-side code, written in PHP, will require a PHP developer that is well- versed in WordPress’ inner workings.

The first step

in leveling up

your skills as

a developer

is learning

object-oriented

programming

for PHP or OOP.

PHP 7

Guest Chapter

by Tom Ewer

WordPress has played a hugely significant role in helping PHP conquer the web over the last 12 years. While WordPress has whizzed through successive versions at an ever-increasing rate during that time, the language that still powers the majority of the platform has remained incredibly stable behind the scenes. Big changes are finally in the offing with the arrival of PHP 7, however, and major WordPress hosts such as WP Engine are already kicking the tires of the latest release and are ready to fully support it for their users. In this chapter, we’ll take a look at the development of PHP 7 to date, what the major changes are, what they mean for WordPress users, and consider whether you should be thinking of making the switch to the new version straight out of the gate. Let’s tee things up with a brief trip down memory lane.

HOW PHP TOOK OVER THE WEB

PHP’s current omnipresence is almost taken for granted these days, but there was very little to suggest that it would go on to dominate the web when it was first cobbled together by Rasmus Lerdorf back in 1994. In many ways, PHP’s rise to the top has been a triumph of good, old-fashioned elbow grease over abstract programmatic concerns. In contrast to competing solutions such as Java and Perl, the language was straightforward enough to attract an audience new to the web, and simple enough on the server side to quickly become a standard install option at hosts worldwide. Put simply, PHP enabled a generation of coders to just get it done. Its early adoption by a host of popular CMS offerings sealed the deal, with WordPress being by far the most significant of them. The PHP 5.x series sprang into life in 2004, and if you’re running WordPress today, you’re almost certainly running a minor version of this under the hood as we speak. The 5.x series has served PHP well over time, but 12 years is a long time between major versions. Sooner or later, a change was bound to come.

PHP 7 FINALLY HEAVES INTO VIEW

Before we get into the nitty-gritty of PHP 7, let’s get some potential naming confusion out of the way. The last stable release of PHP was PHP 5.6 in 2014, so at this stage, you might well be wondering what happened to PHP 6. To cut a long story short, there was a previous attempt at a new major version using the name PHP 6 from 2005 to 2010 that never fully got off the ground, and to avoid muddying the waters, the decision was eventually made to go straight from the 5.x series to PHP 7. PHP 7 has been under active development since 2014, and was officially released in December

  1. Its development arrived at an interesting time in the wider PHP world, as new initiatives such as Facebook’s HipHop Virtual Machine were simultaneously expanding what was previously thought possible with the language.

In this

chapter,

we’ll take a

look at the

development

of PHP 7

to date.

Tests from Zend and WP Engine (among many others) have confirmed the significant improvements we can expect in both speed and performance, and the WordPress Core team has been beavering away at getting the platform ready for the new version since mid-2015.

WordPress performance is significantly improved.

THERE ARE TWO KEY POINTS TO EMPHASIZE HERE:
  1. There are backward incompatible changes that plugin and theme developers will have to take into account going forward.
  2. WordPress’ own commitment to backward compatibility is as strong as ever – both PHP 7 and previous versions will continue to be supported.

From the average end user point of view, it’s fair

to say PHP 7 will be a slow burn in terms of when

they really see the advantages.

Anecdotal evidence from around the web suggests there is still a lot of work to be done on popular themes and plugins before many are ready for the new hotness. WP Engine’s own investigations into the general state of PHP 7 readiness also backed that up, as they now support PHP 7 for their users and have developed a PHP Compatibility Checker plugin

for WordPress users to ensure they don't experience any compatibility issues with themes, plugins, and so on before making the transition to PHP 7.

Taking a broad view, we can expect end user

switchover to PHP 7 to be slow and steady as

the core team, hosting partners, and

developers continue to work towards offering

bulletproof solutions.

Speaking of which, let’s examine whether developers themselves are ready to pull the trigger yet.

WHY DEVELOPERS ARE HOLDING FIRE ON SWITCHING
(FOR NOW)

Developers are (rightly) a cautious bunch at the best of times, and it seems likely the majority will ease into PHP 7 slowly, rather than charging in all guns blazing. Organic factors – such as PHP 7 gradually becoming the default PHP package shipped with various Linux distributions – will help, but don’t expect a stampede any time soon. A developer survey by PHP Classes in the run-up to the official release offers a decent snapshot of sentiment across the community. Respondents were asked three straightforward questions:

  1. Are you going to use PHP 7 in production?
  2. Are you going to use PHP 7 in your development environment?
  3. What is the latest PHP version you are using in production?

You can see the full results over on the survey page, but the range of answers broadly shows around half of the respondents actively considering using it in production in the short- to medium-term future, and roughly the same amount are either already or about to start using it in their development environments:

ARE YOU GOING TO USE PHP 7 IN PRODUCTION?

Yes, I am using already since versions before the first stable 7.0.0 release 21 4% Yes, I want to start using only since the official 7.0.0 version is released 104 19.8% Yes, I will wait a few weeks or months after the 7.0.0 version is released 196 37.3% It depends on the customers that I work for 44 8.4% No, not anytime soon, I need to migrate a lot of my code and that will take me a long time

No, not now, I only plan to use it for future new projects 64 12.2% No, only if my hosting company forces me to use it and does not provide an older version

Other 19 3.6%

Developers

are (rightly)

a cautious

bunch at the

best of times.

PHP

Fundamentals

Like many WordPress developers, the first time I wrote PHP, I didn’t know anything about it or software development in general. As I started to tackle more advanced concepts, I struggled because I had never learned the fundamentals of PHP that were assumed in the materials I encountered. Regardless of your stage in your process of learning PHP as a WordPress developer, it’s important to make sure you know the basics. Regardless of your stage in your process of learning PHP as a WordPress developer it’s important to make sure you know the basics. In this chapter, I will discuss PHP fundamentals: variables, constants, data types, functions, and scope. This knowledge will equip you to learn PHP and other languages, as most of these concepts are fundamental to software development in general.

VARIABLES AND CONSTANTS

The most simple “hello world” PHP program looks like this: echo ‘Hi Roy’; This prints the words, “Hi Roy.” But as our program grows, we might want to print these words more than once, or use conditional logic to decide when or where to print them. While in principle we could just cut and paste those lines of code into multiple locations, it directly violates the “Don’t Repeat Yourself ” (DRY) principle, one of the most sacred principles in software development. To avoid this, store the words “Hi Roy” into a variable before expanding the program, like this: $hi = “Hi Roy”; echo $hi; Now we can reuse this variable to change its value: $hi = ‘Hi Roy’; echo $hi; $hi = ‘Hi Shawn’; echo $hi; In software development, a variable is a value that changes based on the conditions or information passed to the program. When you create a variable and put data in it, that data now exists somewhere on the server as a unique value in RAM. Like variables, constants are another item in which content can be stored. As the name suggests, as opposed to variables — whose values can vary during a request — the content of constants can not. For example, here is a constant we define in our wp-config.php: define( ‘WP_DEBUG’, true ); If I tried to define WP_DEBUG anywhere else on my site, I would get an error because constants never change. That’s why we tend to use them less frequently than variables and primarily in program configuration.

Like

variables,

constants

are another

item in which

content can

be stored.

This is a simple, one-dimensional array, which means it has only one level of depth. Arrays can gain depth by nesting other arrays within them, like this: $posts = [ ‘drinks’ => [ ‘coffee’ => [ ‘10 Things You Always Wanted To Know About Coffee’, ‘8 Worthless Facts About Coffee’, ‘5 Things That Would Matter Except You Need More Coffee’ ], ‘tea’ => [ ‘Tea and Other Alternative Caffeine Delivery Systems?’, ‘Decaf Tea: As Opposed To Coffee, This Is A Good Thing’, ] ], ‘foods’ => [ ‘9 Tasty Vegan BBQ Solutions’, ‘5 Sandwiches of Epic Victory’ ] ]; We would call this a multidimensional array because of its nested structure. Some arrays also have “keys.” We could access the food “key” like this: $food = $post_titles[ ‘food’ ]; Nested keys must be accessed using that hierarchy. You can’t access the coffee key without accessing the drink key. For example, this would generate a warning: $coffee = $post_titles[ ‘coffee’ ]; However, this would work: $coffee = $post_titles[ ‘drinks’ ][ ‘coffee’ ]; Note that if we do not specify keys, then PHP indexes the array using numbers, starting with zero. So to get the second entry in the coffee array we would use the number one like this: $title = $post_titles[ ‘drinks’ ][ ‘coffee’ ][1]; Arrays are mutable. That means that we can change their contents at any time. For example, we could add another item to the array like this: $post_titles[] = ‘8 Fun Facts About Juice’; The entry in the array would get pushed onto the end and numerically indexed, which doesn’t make much sense with our structure. It would be better to define a key for juice and place it there: $post_titles[ ‘juice’ ][] = ‘8 Fun Facts About Juice’;

Arrays can

gain depth

by nesting

other arrays

within them.

FUNCTIONS AND SCOPE

As I mentioned before, part of the reason to have variables is to avoid writing repetitive code that violates the DRY principle. While variables are containers for information, functions are containers for functionality. If we need to do something, we almost always want to encapsulate that functionality in a function. I’m going to discuss functions and scope together now. This is necessary as functions separate code from the rest of the program. Doing so not only keeps things DRY, but also makes that functionality available throughout the program and lets us run it as many times as we need. Functions in PHP are created using the “function” keyword, followed by a name for the function and parenthesis, which might contain function arguments. Function arguments are how we pass information into a function. Inside of a function, there are only variables passed in as arguments. Variables defined outside of that function are not accessible. They are considered outside the “scope.” Let’s consider this function, called slug_get_product: function slug_get_product( $slug ){ return get_post( [ ‘post_type’ => ‘my-product’, ‘post_ name’ => $slug ] ); }

This function is basically a wrapper for

WordPress’ function get_post(). It gets a post

with a specific slug in the post type “my-

product.” Having one utility function for this

saves having to write the same argument set for

get_posts() multiple times. It also means that if

you change the name of that post type, there is

only one line of code to change.

Note that we passed in the variable $slug as an argument. That’s why we could use $slug inside of the function. On the other hand, this wouldn’t work: $slug = ‘red-shoes’; function slug_get_product( ){ return get_post( [ ‘post_type’ => ‘my-product’, ‘post_ name’ => $slug ] ); }

Variables

defined

outside of

that function

are not

accessible.

Object

Oriented

PHP

Object-Oriented PHP helps you create more flexible code by allowing it to be only defined once but used in many places. In this chapter, you will learn the concepts behind Object- Oriented PHP in WordPress and walk through some practical examples.

BEFORE WE BEGIN

It’s important that you try out the various examples provided. While you could do this in a theme template file on a test site, it’s quicker and easier to use the debug console that’s made available by an add-on to Debug Bar , a development plugin. It can be installed separately or as part of the Developer plugin bundle in the repo.

One of my favorites (and the one you should

install) is Debug Bar Console , which gives you

a place to quickly test PHP and MySQL in the

context of your current site configuration. If

you haven’t already installed it, go ahead and

do so now.

METHODS VS. FUNCTIONS

In functional programming, we’re used to working with functions — which, once declared, are always available. In OOP, the functions inside a class are called methods, which are only accessible in the context of that class. When using non-object oriented PHP in your themes or plugins, call a function directly and prefix the function names with a unique slug to avoid conflicts with other plugins or themes. Keep in mind that you should still prefix class names to avoid conflicts with other themes or plugins. In OOP, methods, or functions inside classes, do not need to be prefixed since they are unique to that class. However, remember that you will need to access them through the class. For this example, create two classes. Both will have one method, the class name, which will echo the name of the class. Here are the two classes: hat and shoe. class hat { function class_name() { return “hat”; } }

In OOP, the

functions

inside a class

are called

methods.