Post

PHP Cheatsheet

Ternary operators

Basic True / False Declaration

1
$is_admin = ($user['permissions'] == 'admin') ? true : false;

Conditional Welcome Message

1
echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';

Conditional Items Message

1
echo 'Your cart contains '.$num_items.' item'.($num_items != 1 ? 's' : '').'.';

Conditional Error Reporting Level

1
error_reporting($WEBSITE_IS_LIVE ? 0 : E_STRICT);

Nested PHP Shorthand

1
echo 'Your score is:  '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );

Conditional PHP Redirect

1
header('Location: '.($valid_login ? '/members/index.php' : 'login.php?errors=1')); exit();

ref https://davidwalsh.name/php-ternary-examples

Object Orientated Programming

Object-Oriented Programming (OOP) in PHP for WordPress themes involves structuring your code around objects and classes. Instead of relying solely on procedural programming, where functions are executed one after another, OOP emphasizes the creation of reusable and modular components known as objects.

Benefits of coding WordPress themes in Object-Oriented Programming include:

  1. Modularity and Reusability: OOP promotes modular design, allowing you to create classes that encapsulate specific functionality. These classes can be reused across different parts of your theme or even in other projects, enhancing code modularity.
  2. Code Organization: OOP encourages a more organized code structure by grouping related functions and properties into classes. This makes it easier to understand, maintain, and extend your codebase.
  3. Encapsulation: With OOP, you can encapsulate data and behavior within classes, controlling access to properties and methods. This encapsulation enhances code security and reduces the chances of unintended interference with your code.
  4. Inheritance: OOP allows for the creation of classes that inherit properties and methods from other classes. In the context of WordPress themes, this means you can create a base theme class with common functionality and then extend it for specific theme variations.
  5. Polymorphism: OOP enables polymorphism, allowing different classes to implement the same methods with different behaviors. This flexibility is beneficial when adapting your theme to various requirements.
  6. Easier Maintenance: OOP code tends to be more maintainable and extensible. If you need to make changes or add features to your theme, the modular structure allows you to focus on specific classes without affecting the entire codebase.
  7. Testing and Debugging: OOP facilitates unit testing, as you can test individual classes independently. This can lead to more reliable and easier-to-debug code.
  8. WordPress Core Integration: As WordPress itself increasingly adopts object-oriented principles, coding your themes in an object-oriented manner aligns with the direction of the WordPress ecosystem, providing better compatibility and integration.

Here’s a simple example of an OOP approach in a WordPress theme:

Simple Example

1
2
3
4
5
6
7
8
9
10
11
12
class CustomTheme {
    public function __construct() {
        // Theme initialization code
        add_action('wp_enqueue_scripts', array($this, 'enqueue_styles'));
    }

    public function enqueue_styles() {
        // Enqueue theme styles
    }
}

$custom_theme = new CustomTheme();

In this example, CustomTheme is a class representing your theme, and the enqueue_styles method encapsulates the logic for enqueuing styles. This structure enhances code organization and encapsulation.

Reasons to use OOP

  1. Avoid spagetti code
  2. Reusable code

class vs object

  • the class is the blueprint
  • the object is the building
  • the class defines the object properties like its dimensions and color it also has functions/methods that do stuff like “open door”
  • You can make many building from the one class

Constructors

  • A contructor is a function that will run automatically when you instantiate an object
  • The contructor can take params and because the contructor will run automatically you can pass values into the constructor
  • Use the this keyword to access properties and methods within the class

Destructors

  • Destructors are used for clean up.
  • Closing connections to databases
  • Destructors run when no other reference to certain object

properties

just like variables

1
2
3
4
5
6
7
8
class Calendar {
   public $name;
   }

$calendar = new Calendar();
$calendar->name = "Year Planner";

Constants

CLASS contant

the CLASS constant will give you the name of the class that you are in CLASS must be placed inside a function

Methods / Functions

Public Functions

You can access these anywhere

Private functions

you can only access from inside the class

Protected functions

You can access it from within the class aswell as from any class that extends it its “safer” to not access properties directly. So what you want to do is use a magic __get method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
class User {

    //properties (attributes)
    protected $name;
    protected $age;
    public function __construct($name, $age) {
    	echo 'what ' . __CLASS__  . 'am i in?';
    	$this->name = $name;
    	$this->age = $age;
    }

    //methods (functions)
    public function sayHello(){
    	return 'hello';
    }

    //use the this keyword to retrieve the name from the class
    public function sayGoodbye(){
    	return $this->name .'says goodbye';
    }

    //getter
    public function __get($property) {
    	if(property_exists($this, $property)) {
    		return $this->$property;
    	}
    }

    //setter
    public function __set($property, $value) {
    	if(property_exists($this, $property)) {
    		return $this->$property = $value;
    	}
    	return $this;
    }

}

class Customer extends User {

    //properties
    private $balance;

    public function __construct($name, $age, $balance) {
    	//get the name and the age from the constructor in the parent class
    	parent::__construct($name, $age);
    	$this->balance = $balance;
    }

    //methods
    public function pay($amount) {
    	return $this->name . ' paid $' . $amount;
    }

}

$customer1 = new Customer('dans', 33, 400);
echo $customer1->pay(500);

//create the new user
$user1 = new User('dan', '37');

//access and echo the name property
echo $user1->name;
echo $user1->age;
//class Customer extends User { }
//access and run the sayHello method
//echo $user1->sayHello();
$user1->**set('age', 41);
echo $user1->**get('age');

//get_object_vars will create and array out of an objects properties

$myObj = new class1;
$arr = get_object_vars($myObj);
	foreach($arr as $key=>$val) {
		echo $key | $val;
	}

more info

Speed Coding ACF With OOP

When it comes to speed coding custom Wordpress that use an ACF based block based page builder system. Discovering object oriented programming was a real game changer.

Using Object Orientated Programming (OOP) with your WordPress Advanced Custom Fields (ACF) is a match made for impatient web developers like me. I’m aware that a web project has so many critical aspects tjat I want to be coding at maximum efficiency and reusing code snippets effectively.

This way we can keep template files cleaner by allocating much of the logic into the php class files. Reduce your code bloat and keep template files readable.

  • It promotes dryer code, less spagetti code.
  • The classes can be reused from project to project
  • speeds up code output for common ui elements

Add your ACF code to a method

Discovering this simple technique was a real game changer for me. For years i was looking for a way to reduce repetitive coding tasks. OOP was my saviour in this regard.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php

/**
 * acf image field class declaration
 */
class AcfImage
{

   /**
      * acf field name must be called 'image'
      * pass in the css class
      */
   public function my_image($css_class)
   {
   $image = get_sub_field( 'image' ); ?>
			<?php if ( $image ) : ?>
				<img class = " <?php $css_class; ?>" src="<?php echo esc_url( $image['url'] ); ?>" alt="<?php echo esc_attr( $image['alt'] ); ?>" />
			<?php endif; ?>
   <?php
   }
}

/**
 * output the image with custom css class
 */

//initiat
$my_image = new AcfImage('banner__image');

//output
$my_image->my_image('css_class');

The block class

Now the above code is simple but it but it can be expanded upon. What if we had a class called block and within block we had methods for all your standard web development patterns

  • image
  • title
  • text
  • link
  • banner
  • slideshow
  • cards
  • blog_news_feed

The idea is you can keep reusing the block class from project to project. Initiating Objects as you need them.

Acf block page builder

See the acf block page builder in action

Dynamically include php files

Organising php code into “include” files can help keep your codebase organised. You can even reuse code by simply including it wherever you need.

Include all the php files in the directory automatically

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 // --------------------------------------------------------------------------
 //   Include Utilities
 // --------------------------------------------------------------------------

 foreach (glob(dirname(__FILE__) . "/lib/utilities/*.php") as $filename) {
   require_once $filename;
 }

 // --------------------------------------------------------------------------
 //   Include Configuration
 // --------------------------------------------------------------------------

 foreach (glob(dirname(__FILE__) . "/lib/config/*.php") as $filename) {
   require_once $filename;
 }

 // --------------------------------------------------------------------------
 //   Include Post Types and Taxonomies
 // --------------------------------------------------------------------------

 foreach (glob(dirname(__FILE__) . "/lib/content/*.php") as $filename) {
   require_once $filename;
 }

 // --------------------------------------------------------------------------
 //   Include Tweaks
 // --------------------------------------------------------------------------

 foreach (glob(dirname(__FILE__) . "/lib/tweaks/*.php") as $filename) {
   require_once $filename;
 }
This post is licensed under CC BY 4.0 by the author.