




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
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
1 / 103
This page cannot be seen from the preview
Don't miss anything!





























































































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.
This ebook will equip you with the knowledge and skills you need to get started with object- oriented PHP as a WordPress developer, including:
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.
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.
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.
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
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.
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.
Speaking of which, let’s examine whether developers themselves are ready to pull the trigger yet.
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:
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:
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.
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 ] ); }
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 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.
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.