BuiltByCactus

Engineering Handbook

Code Style

PHP written inside WordPress should follow the WordPress PHP Coding Standards as well as the Human Made Standards.

File Fucntion

PHP files should either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but should not do both

File Naming

Files containing a class should be named class-<classname>.php, all lowercase, to fit with the WordPress coding standards.

The main file for themes is functions.php in the theme directory. This file should be the only one to contain run code. This file should also register necessary autoloaders.

Yoda Conditions

We love Yoda conditions, they stop accidental assignment of variables and therefore should be used wherever possible!

// No
if ( $text == 'Hello, World' ):

// Yes
if ( 'Hello, World' == $text ):

Anonymous Functions (Closures)

Closures are allowed but please remember that if you pass a closure into an add_action or add_filter it can’t be unhooked later on.

For this reason we generally discourage their use when hooking into filters etc.

Arrays

When creating arrays, opt for the short-array syntax [] over the standard one array()as it’s easier to read and more compact.

// No
$array = array(
    'something' => 'fun',
    'args' => array(
        'old' => 'syntax',
    ),
);

// Yes
$array = [
    'something' => 'fun',
    'args' => [
        'old' => 'syntax',
    ],
];

Visibility (Public/Protected/Private)

Class methods and properties should always be marked with a visibility keyword, either public, protected or private. Generally, protected should be used in favour of private, as private is overly restrictive on subclasses and can lead to bad practices down the line.

PHP in Templates

When using PHP in templates then try to open and close PHP tags on the same line.

// No
<?php
foreach ( $blogs as $blog ) {
?>
    <div>
        <?php echo esc_html( $blog->ID ); ?>
    </div>
<?php
}
?>

// No
<?php foreach ( $blogs as $blog ) { ?>
    <div>
        <?php echo esc_html( $blog->ID ); ?>
    </div>
<?php } ?>

// Yes
<?php foreach ( $blogs as $blog ): ?>
    <div>
        <?php echo esc_html( $blog->ID ); ?>
    </div>
<?php endforeach ?>

Sessions

Unless we’re using WooCommerce’s sessions or the WP Admin sessions then leave them be. There’s very little need for them and they can cause unwanted issues.

If you really need sessions, talk it through with the project lead and see if you can find a better solution. If you do need to use them, then use PHP’s native session handler and do not store them in the database.