How to specify a zeroed UUID in MySQL

Photo by Chris Barbalis on Unsplash

Working on a recent project that dealt with data synchronization across disparate systems, I realized I could not use the oh-so-easy INT for primary keys. Instead I chose to use the emerging best practice of employing UUIDs for distributed databases.

However, the library functions in Go are not friendly with for MySQL’s NULLs thus it helps to avoid NULLs in your schemas when writing Go apps that use MySQL.

So how to represent a “null” UUID? The value I chose was simply a zeroed UUID:

// UUID_TO_BIN() requires MySQL 8+
UUID_TO_BIN('00000000-0000-0000-0000-000000000000',true)

Too much typing tempts typos

But doing so created a conundrum; how to reference it in views and queries without:

  1. ) Having to type so much each time I reference said value in a query, and
  2. ) More importantly, how to ensure against accidental typos?

What I needed as a UUID literal for a zeroed UUID, and you think such a thing would be easily findable via a google, but no dice. (I guess most people don’t avoid NULLs?)

A short “literal”

The “obvious” CAST(0 AS BINARY) kept failing because MySQL was interpreting 0 as '0' and encoding it as 30 hexadecimal. What I needed as a actually binary 0, this b'0' to the rescue.

Still, CAST(b'0' AS BINARY) was failing; why? Ah, because that expression returns the shortest binary. What I needed was BINARY(16), hence the following is exactly what I needed:

// Equal to UUID_TO_BIN('00000000-0000-0000-0000-000000000000',true)
CAST(b'0' AS BINARY(16))

Honorable mentions

My primary use for this need was for use in the WHERE clause, so I found several other expressions that worked for that purpose too. But I did not use them because they are all cryptic and would hide my intention to a causal reader of the code.

Still, there were interesting to me so I thought I would share them:

  1. WHERE HEX(parent_guid)=REPEAT('0',32)
  2. WHERE REPLACE(HEX(parent_guid),'0','')=''
  3. WHERE SOUNDEX(HEX(parent_guid))=''
  4. WHERE parent_guid=(SELECT uuid FROM uuid LIMIT 1)
  5. WHERE parent_guid=CAST(b'0' AS BINARY(16))

How do those work?

  1. Using HEX() on a zeroed UUID gives us '00000000000000000000000000000000'. So clearly HEX() on our zeroed UUID will equal REPEAT('0',32).
  2. If you TRIM() the zeros off of '00000000000000000000000000000000' you get an empty string: ''
  3. If you SOUNDEX() a string of zero characters you get an empty string: ''. This was my favorite alternate simply because if was the shortest.
  4. If you create a one record, one field table containing a zeroed UUID value, you can of course compare against it in a query.
  5. Lastly, this is how I am using my “literal” for a zeroed UUID in the WHERE clauses of my MySQL VIEWs that need them.

And if you know of a better way, please share in the comments.

PHP delegation vs. GoLang type embedding

Photo by Martin Reisch on Unsplash

One of the things I like the most about the Go programming language that I really wish PHP had is its type embedding.

And while legitimate Gophers know that Go is not exactly an object-oriented language, it has many features that allow leveraging OOP development experience so please permit me to discuss type embedding from an OOP perspective so it will be easier to understand by OOP developers.

PHP composition using delegation

In OOP languages like PHP, we have “inheritance” which allows classes to use the functionality of a more abstract class without having to implement it.

Consider a Block class for a desktop app with content properties and a render() method. With inheritance a developer can declare a AdvertBlock class which can inherit from the Block class and will automatically gain the Block‘s content property.

class Block {
    public $content;
    function render() {
        echo $this->content;
    }
}
class AdvertBlock extends Block {
    function __construct($advert) {
        $this->content = $advert;
    }
}
$avb = new AdvertBlock("<div class="ad"></div>");
$avb->render();

But in recent years, “thought leaders” in the development world have decided that Inheritance is bad and can no longer be discussed in polite company. The new king is Composition, and it is what everyone should be doing.

The problem is, if you use composition instead of inheritance in most OOP languages –– like PHP –– you end up having to write lots of methods that do nothing other than delegate from the contained class (e.g. Block) to the classes contain it (e.g. AdvertBlock), and you have to somehow provide an instance of the contained class when you instantiate it (as you see here in __construct()):

class AdvertBlock {
    private $_block;
    function __construct($block,$advert) {
        $this->_block = $block;
        $this->content = $advert;
    }
    function render() {
        $this->_block->render();  
    }
}
$avb = new AdvertBlock(new Block(), "<div class="ad"></div>");
$avb->render();

Now the above might not look so bad, but consider when you are dealing with tens of classes and and tens of methods for each class where you need to implement this delegation. That is a lot of boilerplate code to write (that, frankly, the language should handle for you.)

Worse consider when you add a method to one of your contained classes? Now you have to go back to each containing class and add a delegate method as well. Ugh.

Of course in PHP you can actually delegate automatically with the __call()magic method, but that is tedious to implement in all your classes, it has significant performance penalties to consider, and you still have to add a PHPDoc comment if you want your IDE to provide autocomplete and to stop flagging as an error. (And I did not even mention delegating properties via __get() and __set() methods!):

/**
 * @method render() void
 */
class AdvertBlock {
    private $_block;
    function __construct($block,$advert) {
        $this->_block = $block;
        $this->content = $advert;
    }
    function __call($method, $args) {
        $value = null;
        foreach( get_object_vars($this) as $name => $value ) {
            if ( method_exists( $this->$name, $method ) ) {
                $value = call_user_func_array([$this->$name,$method],$args);
                break;
            }
        }
        return $value;
    }
}

Still, even with all these downsides I still use this approach in all of my PHP projects because it is mostly better than not.) Ironically, one of the best ways to handle including this type of __call()method in all your PHP classes is to use some sort of BaseObject() class that you have all your other classes extend from. But I digress…

Go composition using type embedding

Once again, Go is not really an object-oriented language; one of the main things it does not support is inheritance. It also does not have classes, although it has structs which are a reasonable facsimile for those coming to Go from other OOP languages.

Since Go does not provide inheritance you must use composition for any sharing of functionality across structs. But here is where Go shines with its type embedding. Go provides automatic delegation when you embed at type; you do not have to maintain it like you do with PHP.

Let us revisit our simple Block and AdvertBlock example, this time using Go:

package main
type Block struct {
    Content string
}
func (b Block) render() {
    print(b.Content)
}
type AdvertBlock struct {
    Block
}
func NewAdvertBlock(a string) AdvertBlock {
    return AdvertBlock{Block{Content:a}}
}
func main(){
    avb := NewAdvertBlock("<div class=\"ad\"></div>")
    avb.render()
}

Easy, peasy!

Even better, you can run it in the Go Playground and/or iyou can tweak the code to see how it behaves given different code choices. Try changing the Block declaration embedded in AdvertBlock to *Block and see what happens (*Block means “a pointer to a Block.)


Proposal: Contracts in Go (Not Generics)

Photo by Cytonn Photography on Unsplash

#Update

When I wrote this I did not remember that the draft design for Go2 generics chose to use the name “Contracts” for a new language feature to provide a Go-idiomatic response to generics.

Still, I stand by my use of the name contracts for this proposal as I think it is more in line with the use than the programming industry and used for decades, and that would the Go team named contracts would be better if they renamed it “Constraints”.

#Discussion

Discussion for this proposal is (mostly?) on Github.

Preface

I wanted to write this as a Go Experience Report (like this one), but my I felt that it would have simply taken simply too much time to explain my specific used case, and by then I would have lost the reader. So I decided instead to simple create a proposal instead.

Suffice it to say that it was my experiencing difficulties during development that caused me to write this, not a pie-in-the-sky desire for some shiny new feature. So I hope those in the Go community who prefer experience reports can forgive me for this transgression.

Problem Statement

In my experience, there are generally two broad use-cases for interfaces. The second is what Go is exceptional for; the one-method, implicitly-implemented “-er” type interface. I cannot gush enough how brilliant these are and how wonderfully they encourage serendipitous reusability.

That said, there is another type of broad use-case for interfaces, and it is the one commonly recognized by most other programming languages; the idea of a contract between caller and callee. In my experience I have generally seen the need for these when creating an extension API.

Basically this concept would be useful in Go when you want to explicitly indicate that a package is to be used as an extension for application code and this concept is usually described as a contract.”

An example of the type of extension might be a database driver — what they call a “dialect” — for GORM.

Proposed Addition

“Contracts” would be a new type in Go and would allow a developer to define a set of interfaces to comprise a contract plus then be able to reference the contract in a struct to enforce its usage

If contracts of this nature existed, maybe GORM would have used a contract and instead and created a collection of small interfaces rather than one large interface?

Example Declaration

Using the GORM Dialect type for our example, with a contract it they could make it look like this:

type Dialect contract {
	NameGetter
	DBSetter
	VarBinder
	Quoter
	DataTyper
	IndexVerifier
	ForeignKeyVerifier
	IndexRemover
	TableVerifier
	ColumnVerifier
	ColumnModifier
	LimitAndOffsetConstrainer
	DummyTableSelecter
	LastInsertIDReturningSuffixer
	DefaultValueStringer
	KeyNameBuilder
	CurrentDatabaseGetter
}

And here is what each of those interfaces could look like:

type NameGetter interface {
	GetName() string
}
type DBSetter interface {
	SetDB(db SQLCommon)
}
type VarBinder interface {
	BindVar(i int) string
}
type Quoter interface {
	Quote(key string) string
}
type DataTyper interface {
	DataTypeOf(field *StructField) string
}
type IndexVerifier interface {
	HasIndex(tableName string, indexName string) bool
}
type ForeignKeyVerifier interface {
	HasForeignKey(tableName string, foreignKeyName string) bool
}
type IndexRemover interface {
	RemoveIndex(tableName string, indexName string) error
}
type TableVerifier interface {
	HasTable(tableName string) bool
}
type ColumnVerifier interface {
	HasColumn(tableName string, columnName string) bool
}
type ColumnModifier interface {
	ModifyColumn(tableName string, columnName string, typ string) error
}
type LimitAndOffsetConstrainer interface {
	LimitAndOffsetSQL(limit, offset interface{}) string
}
type DummyTableSelecter() interface {
	SelectFromDummyTable() string
}
type LastInsertIDReturningSuffixer() interface {
	LastInsertIDReturningSuffix(tableName, columnName string) string
}
type DefaultValueStringer() interface {
	DefaultValueStr() string
}
type KeyNameBuilder() interface {
	BuildKeyName(kind, tableName string, fields ...string) string
}
type CurrentDatabaseGetter() interface {
	CurrentDatabase() string
}

Isn’t this more like idiomatic Go?

Example Usage

Then to use a contract in a struct, just embed it as you would another struct. The following example embeds our hypothetical contract named gorm.Dialect. Very simple:

type OracleDialect struct {
    gorm.Dialect
    // Properties go here
}
// Methods go here

Additional Enhancements

Beyond the simple addition of contracts there are a few other features I think would really be beneficials for these proposed contracts.

Allow Interfaces to be Optional

One of my biggest complaints with interfaces in other languages is their fragility. They can never accept backward compatible changes once they have been “released into the wild.” The ability to define implementation of an interface as optional would go a long way to making contracts more resilient over time. It would also allow contract designers to specify which methods implementers can ignore if they do not need them.

Revisiting our Dialect contract from above, here is what it might look like with an optional keyword:

type Dialect contract {
	NameGetter
	DBSetter
	VarBinder
	Quoter
	DataTyper
	IndexVerifier
	ForeignKeyVerifier
	IndexRemover
	TableVerifier
	ColumnVerifier
	ColumnModifier
	LimitAndOffsetConstrainer
	DummyTableSelecter
	LastInsertIDReturningSuffixer optional
	DefaultValueStringer optional
	KeyNameBuilder
	CurrentDatabaseGetter
}

Allow Interfaces to be Added

Now I realize that over time developers might add methods to contracts and mark them as optional to support backward compatibility even though they might not be optional for newer use-cases. If this is seen as a significant problem then maybe added [`<ver_tag>`] could be used to specify that a method is in fact optional but only for backward compatibility reasons and that newer implementers should use it.

Contacts would also allow IDEs like GoLand to optionally enforce the need the interface to be implemented, if they chose to do so.

Counter Argument

So what do I anticipate the counter argument to be?

Go does not need a new type

I assume a seasoned Go developer might say:

“We can already do “contracts” just by embedding an interface into another interface. We don’t need a new named — let’s keep Go — and just allow interfaces to be explicitly implemented in a struct to address this use-case.”

And they would be right. Frankly, that was my first thought too.

Rebuttal

But then I remembered one of the best things about Go interfaces is they are implicit, and when small they can empower serendipitous reusability. But Go currently encourages large interfaces for these use-cases, and from an idiomatic perspective, I believe that is bad behavior.

Contracts would discourage large interfaces

If Go adds a new contract type, and the contracts only supports aggregation of interfaces with not direct inclusion of method signatures then many small interfaces would actually be encouraged.

There would also be be a clear and distinct difference in intended use-case for contracts vs. interfaces.

Summary

So, since:

  1. Programming educators have been using “contract” to explain interfaces for decades,
  2. A contract type would obviously be easy to reason about
  3. This is a use-case for interfaces that Go does not yet accommodate,
  4. I do not think this would make Go programs more fragile or complex, and
  5. (I think) it would not have any backward compatibility issues.

I contend this would be a great addition to Go.

What do you think?

GoLang Strict Typing and Interface Slices

Photo by Louise Lyshøj on Unsplash

This is a GoLang Experience Report.

…but you cannot define the rows parameter as type []RowInserter because []interface{} won’t match it, even though RowInserter is itself an interface.

Background

I am relatively new to programming Go, but I have been developing software professionally in a variety of programming languages on and off since the late 80’s. Go’s concept of a language in service of software engineering resonates with me greatly, and as such I am very interested in learning and using idiomatic Go.

Regarding my experience report, an advocate of adding generics to Go will read this post and declare it illustrates why Go needs generics. I however, am not a fan of generics, at least not how they have been implemented in other C-like languages. Thus I would prefer Go find an easier-to-reason-about method for handling concerns like I am reporting.

Scenario

Consider a scenario where you have a slice of a concrete struct. Let us call that struct’s type Item for our example. And let us also assume these Items implement a RowInserter interface which requires an InsertRow() method be declared:

type Item struct {
   id int
}
type RowInserter interface{
    InsertRow()	
}
func (i *Item) InsertRow() {
   fmt.Printf( "Item id=%d inserted.\n",i.id )
}

Since, for many of my use-cases, the insertion of rows is fairly generic I would like to create a general-purpose package with a method you just pass a slice of Items to and have it loop through the rows to insert the item by calling the items’ InsertRow() method for each item.

Here is a main() that creates there items and then calls my desired InsertRows() function as I just described:

func main() {
   items := make([]*Item,3)
   for i := range []int{1,2,3} {
	items[i] = &Item{i}
   }
   InsertRow(items) // This won't work...
}

But of course the above does not work.

Instead we need to first loop through the slice of Items and add them to a slice of interface{}.

We could have littered our main() with this code, but instead I created an InsertItems() function that does the looping for us:

func InsertItems(items []*Item) {
    rows := make([]interface{}, len(items))
    for i, item := range items {
        rows[i] = item
    }
    InsertRows(rows)
}

Now we can implement our “generic” InsertRows(). However, and here is one of the main tricks, you cannot define the rows parameter as type []RowInserter because []interface{} won’t match it, even though RowInserter is itself an interface:

func InsertRows(rows []interface{}) {
    for _,r := range rows {
        r.(RowInserter).InsertRow()
    }
}

I have added all the the above in the Go playground. Please try it for yourself.

(Or maybe I just do not know how to make this easier to work with? Please comment if you know otherwise.)

Suggestion

Since InsertRows() accepts a parameter that is a slice of interface{} it would not violate type safety, other than in the most rigid perspective, for a slice of another type to be passed in and automatically converted to a slice of interface assuming the types satisfy the interface used.

Even better would be for when we want to pass a slice of types (e.g. []*Items) that implement a specific interface (e.g. RowInserter) are passed to a function that accepts a slice of that interface (e.g. []RowInserter) then Go could validate the elements of the slice for type safety and not the entire composite type.

Then my example could be simplified greatly to the following, and would also be much easier to reason about:

package main

import (
    "fmt"
)

type Item struct {
   id int
}

func main() {
   items := make([]*Item,3)
   for i := range []int{1,2,3} {
	items[i] = &Item{i}
   }
   InsertRows(items) 
}

func (i *Item) InsertRow() {
   fmt.Printf( "Item id=%d inserted.\n",i.id )
}

type RowInserter interface{
    InsertRow()	
}

func InsertRows(rows []RowInserter) {
    for _,r := range rows {
        r.InsertRow()
    }
}

Also, this same should apply for maps as well asfor slices, assuming the map keys are the same type.

Practical Object-Oriented Programming for WordPress Developers: A Tutorial Series

Goals of this Tutorial

Welcome to this ongoing series whose goal is to teach Object Oriented Programming to WordPress developers.

This series will teach you in a unique manner compared to traditional tutorials on OOP and based on my several decades of instructional experience. Using this approach it I believe it will be easier for a WordPress developer to learn OOP than from most other tutorials on the topic.

Not only will you learn OOP you will also learn many practical techniques you can apply to your projects immediately, something else that most OOP tutorials I have seen do not provide.

Table of Contents/Installments

Here are the installments of this series I have written thus far, and the name of the next one planned:

  1. Understanding objects in PHP for WordPress
  2. A review of WordPress’ built-in classes

But is this Practical OOP series for me?

You build WordPress sites, themes and/or plugins for customers, clients, your employer and/or yourself.  You are at least somewhat comfortable with PHP coding but still do not really understand “Object-Oriented Programming.” That said, you have been told by countless other developers that you should be programming this way.   But try as you might,  you have struggled to learn what we programmers call OOP, for whatever reason. Maybe its confusing tutorials, or maybe it’s just a lack of time. Whatever the case, you are still not there yet.

Is this you?  Essentially a skilled WordPress “developer” but still a beginner when it comes to Object Oriented Programming?

If yes then you are the audience I envision for this series of installments. I  designed this series to bring you up to speed on OOP for WordPress painlessly and easily while providing you with real world code you can put into practice immediately.

But if you are a fairly experienced programmer then the first few installments will almost certainly be too simple for you. But if you are not yet at guru status it will still be best to wait until for the 3rd or later installments of this series.

On the other hand if you are an OOP for WordPress guru you can of course skip the entire series. 🙂

Why is OOP so hard to learn?

Skip this section to jump ahead to installment 1 and start learning OOP right away.  

We could ponder at least why so many have struggled with OOP. But instead I would like to suggest that learning OOP can be hard because almost every tutorial that attempts to teach it starts with the what of Object-Oriented Programming before it ever makes the case for why you should use OOP.

Chances are you have read tutorials on OOP and they quickly tell you that OOP is a coding style and that it differs from procedural programming. Then they quickly rattle off how OOP requires encapsulation, abstraction, inheritance and polymorphism long before the expose you to the programming problems that OOP can solve.

These tutorials either use abstract examples that don’t apply to WordPress, or their examples as so overly complex that you do not learn how to use OOP in the practical ways you need need to solve problems today. Given this is it no wonder that so many people struggle with or fail to appreciate the practical benefits of OOPs. Instead OOP just starts feeling like a bunch of rules presented as unquestionable programming dogma something that only the most pedantic can warm up to.

I know. I started my professional career as a programming trainer and that is exactly how I taught OOP at the time. I was religious about it at the time. The OOP books at the time and my college professors who taught OOP always started with the what, never with the why or the practical how so at first I emulated them.

But since those early days several decades ago I learned people struggle when concepts are presented ahead of why they matter. I learned this when I found myself struggling with new concepts when I have yet to understand the problems they solve.

So that is how this series intends to differ; I first want to give you a reason to care before I indoctrinate you with OOP jargon.

Without further adieu, let us dive in.

Practical OOP for WordPress Installment 1: Objects

This is the first of an ongoing series whose goal is to teach Object Oriented Programming to WordPress developers.  Check out the table of contents for the list of other installments.

This first installment starts off slow and easy to ensure we don’t loose anyone. But fear not, future installments will accelerate the pace and challenge all but the most advanced OOP gurus in the WordPress community.

You’re already using OOP with $post

You may not realize it, but if you are modifying PHP in themes and/or writing plugins you are already using OOP.  The global $post variable is itself an Object.

content-front-page.php
The theme template file content-front-page.php from WordPress’ Twenty Seventeen theme.

Maybe you have yet to directly use $post but you have almost certainly used it indirectly. The template tags (a.k.a. PHP functions) have_posts(), the_post(), get_post_format(), comments_open(), get_comments_number(), comments_template() and the_post_navigation() found in the template below all create, update and/or access the global $post variable:

single.php
The theme template file single.php from WordPress’ Twenty Seventeen theme. Reformatted for presentation purposes.

Understanding $post as object

WordPress functions frequently assume that there is a global variable named $post because WordPress’ bootstrapping code ensures the variable exists with a valid value inside every theme template file (except for within the 404 template, for hopefully obvious reasons.) And that is why functions like get_post_format() and the_post_navigation() are able to assume a global $post variable exists.

In addition, the_post() function of The Loop ensures that $post is continually updated for an archive page.

The global $post variable typically contains a value of type 'object' although at times$post may contain a value of null if a plugin or theme tries to load a post that does not exist (which often indicates a bug, but not always.) 

Assuming you create a Page in WordPress ($post_type==='page') that uses the following page template you will see that this page outputs the word object:

<?php
// Template Name: Output 'type' of $post
global $post;
echo gettype( $post );  // Outputs: object

Code Snippet #1: Using gettype() to inspect
the data type of an object variable.

Objects vs. other variable types

Variables that contain Object values differ from variables that contain other values, such as values of type String, Integer, Float or Boolean. Objects instead contain a collection of contained values, each of which themselves have their own type.

Actually objects are very similar to Arrays in the respect that both arrays and objects contain multiple values.  To illustrate lets compare to the use of an array, using a code pattern with which you might already be familiar:

$post_id = wp_insert_post( array(
   'post_type'   => 'post',
   'post_status' => 'publish',
   'post_title'  => 'Practical Object-Oriented Programming...',
));

Code Snippet #2: Using an array() to pass
arguments to wp_insert_post().

We can of course represent that same information as an object instead. Interestingly wp_insert_post() will accept either an array or an object. For example the following is functionally identical to the previous code:

$post_obj = (object) array(
   'post_type'   => 'post',
   'post_status' => 'publish',
   'post_title'  => 'Practical Object-Oriented Programming...',
); 
$post_id = wp_insert_post( $post_obj );

Code Snippet #3: Using an (object)array() cast
to pass arguments to wp_insert_post().

Here we used a PHP language feature known as casting which converts  (a.k.a “casts”) a value of type array to type object instead. And this is a very convenient way to create object some of the time.

But there is a more explicit way to create an object in PHP and that is with the new statement.

Creating new objects

The more flexible way to create an object is to use the new statement.  The new statement allows you to specify the name of a Class for the object you want, but let us not worry about the specifics of classes just yet; we’ll cover them in our next installment of this Practical OOP for WordPress series.

To create a value of type 'object' you can reference stdClass which has been included in PHP since the earliest days and simply prefix it with new to create an object:

$post_obj = new stdClass();

Code Snippet #4: Creating a new
object of class stdClass

The object created with new stdClass is an empty object, one without any contained values.  It is equivalent to calling (object) array().

Object literals?

Note that unlike arrays, there is no literal syntax for creating an object besides, of course, specifying a literal array() and then casting it to object. Which is what we did in code snippet #3.

Accessing an object’s contained values

Once you have a new object you can add contained values to it using the “pointer” syntax (at least that is what I call it as there does not seem to be an official name.) 

The pointer syntax is a dash followed by a greater-than (->), and in practice is written like this:

$object->value_name

Code Snippet #5: Syntax for access an
object’s contained values.

Updating the object’s contained values

Using the pointer simple variable assignment syntaxes let’s assign values to our $post_obj:

$post_obj = new stdClass();
$post_obj->post_type = 'post'; 
$post_obj->post_status = 'publish'; 
$post_obj->post_title = 'Practical Object-Oriented Programming...'; 
$post_id = wp_insert_post( $post_obj );

Code Snippet #6: Assigning values to a stdClass object
before passing to wp_insert_post().

Note that the above code is functionality identical to code snippets #2 and #3.

The properties of an object

I have shown you the contained values of an object — which are more correctly referred to as “properties” of a object — include a classification not so ironically called a “Class.”  And the one example seen this far has been named stdClass.

In addition an object also has zero or more contained values, and these contained values has a special name in OOP; they are called Properties (see what I did there?)

Looking back at the properties we’ve added to our $post_obj variable thus far include post_type, post_status and post_content.  And we can both assign/set and access/get those properties, i.e.:

/* 
 * Assignment: Sets `post_type` to the literal value 'post'.
 */
$post_obj->post_type = 'post';    

/* 
 * Accessing: Gets `post_type` property and assigns to $post_type.
 */
$post_type = $post_obj->post_type 

Code Snippet #7: Assigning and accessing
values of an object.

Revisiting the $post object

Back to the $post object.

Earlier we saw that $post is updated by The Loop in a theme template, and that many template tags in WordPress(a.k.a. PHP functions) recognize and interact with this $post object.

We also saw a very similar object $post_obj which is much like $post as both have the properties  post_type, post_status and post_content.  Let’s go ahead and look at the properties of a $post object.

Drop the following into new theme template, assign it to a page, and then “view” that page:

<?php 
// Template Name: Display properties of $post
echo '<ul>';
foreach( $post as $property_name => $value ):
    echo "<li>{$property_name}</li>";
endforeach;
echo '</ul>';

Code Snippet #7: Code to output the
properties of the
$post object.

Your page output should contain the list of property names available in the $post object, i.e. $post->ID and $post->guid are both valid property name references:

- ID                                                         
- post_author                                                
- post_date                                                  
- post_date_gmt                                              
- post_content                                               
- post_title                                                 
- post_excerpt                                               
- post_status                                                
- comment_status                                             
- ping_status                                                
- post_password                                              
- post_name                                                  
- to_ping                                                    
- pinged                                                     
- post_modified                                              
- post_modified_gmt                                          
- post_content_filtered                                      
- post_parent                                                
- guid                                                       
- menu_order                                                 
- post_type                                                  
- post_mime_type                                             
- comment_count                                              
- filter                                                     

The $post object’s class

One additional things you’ll learn about our $post_obj object from code snippets #2, #3, #4 and #6 is that they are each fundamentally different from the$post object in code snippets #1 and #7.  In the former the object’s class is stdClass and for the latter it is WP_Post.

Unlike the generically-named stdClass — which is built into PHP — there is actually a PHP source code file in WordPress core that defines the properties of a WP_Post classWhat classes are for and how to define them is a topic for the next installment of this series.

Not that the WordPress core files that define the WP_Post class also define that classes methods, but what methods are and how we’ll use them will need to wait for a future post.

On the other hand, if you are anxious to peek inside you can find the code that defines WP_Post in the following file within your WordPress installation:

/wp-includes/class-wp-post.php                                      

Lesson review

So what did we learn in this first installment?

  1. You are already using OOP (to an extent) with the $post object.
  2. WordPress core automatically makes the $post object available inside theme template files.
  3. The $post object is also updated by the_post() function of The Loop when in multi-post pages such as index.php and any archive templates.
  4. Many template tags aka PHP functions such as the_title()the_content() and next_post_link() assume a $post variable exists and that it contains a valid value.
  5. Calling gettype( $post ) normally will return a string value of 'object' but at times may return 'NULL'.
  6. Both arrays and objects can be empty, and they can also group a collection of one or more contained values.
  7. You can create an object by casting an array to an object using the casting syntax of (object) array( ... ).
  8. You can also create an object using the new statement.
  9. When using the new statement you must specify a Class name.
  10. The default class name in PHP is stdClass and has been part of PHP since the early days.
  11. When first created with new an object of class stdClass contains no values.
  12.  You assign/set and access/get the contained values of an object using (what I call) the “pointer” syntax: $object->value_name = $value; and$value = object->value_name;, respectively.
  13. The contained values of an object are called Properties in OOP terminology.
  14. The properties  of WordPress’ ubiquitous $post object are ID, post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_content_filtered, post_parent, guid, menu_order, post_type, post_mime_type, comment_count and filter.
  15. That same $post object is creating from a class named WP_Post.
  16. The WP_Post class used to creates the $post object also contains something called Methods.
  17. The code defining WP_Post can be found in /wp-includes/class-wp-post.php.
  18. And finally, we’ll learn more about PHP Classes and Class Methods in the next and a future installment of this Practical OOP for WordPress series, respectively.