Web Development Articles
PHP Null Coalescing Operator ??
$var1 = null; // it's null$var2 = 15;$var3 = $var1 ?? $var2; // the value is 15
OR
$var1; // it's undfefined
$var2 = 15;
$var3 = $var1 ?? $var2; // the value is 15
In Example 1 above the value of $var3 will be the value of $var2. This is because value of $var1 is null or undefined. If $var1 is any value besides null, the value of $var3 would be the value of $var1. That case is displayed in Example 2 below.
In Example 2:
$var1 = 3;$var2 = 15;$var3 = $var1 ?? $var2; // the value is 3PHP Match Expression (match)
PHP Match Expression (match)
The PHP match expression is a powerful feature introduced in PHP 8.0 that provides a more concise and flexible alternative to switch statements.
Basic Match Syntax
$result = match ($value) {
pattern1 => expression1,
pattern2 => expression2,
// ...
default => default_expression,
};
Comparison switch vs match
// switch statement
switch ($statusCode) {
case 200:
$message = 'OK';
break;
case 404:
$message = 'Not Found';
break;
case 500:
$message = 'Server Error';
break;
default:
$message = 'Unknown';
}
// match equivalent
$message = match ($statusCode) {
200 => 'OK',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown',
};
Various Usage Examples:
// multiple conditions
$result = match ($httpCode) {
200, 201, 202 => 'Success',
400, 401, 403 => 'Client Error',
500, 501, 502 => 'Server Error',
default => 'Unknown',
};
// Match uses strict comparison (===)
$result = match ($value) {
0 => 'Integer zero',
'0' => 'String zero',
false => 'Boolean false',
default => 'Other',
};
// Complex Expressions
$age = 25;
$category = match (true) {
$age < 13 => 'Child',
$age < 20 => 'Teenager',
$age < 65 => 'Adult',
default => 'Senior',
};
// returning different types
function processValue($value) {
return match ($value) {
'int' => 42,
'string' => 'Hello World',
'array' => [1, 2, 3],
'bool' => true,
default => null,
};
}
// Using with arrays
$user = [
'role' => 'admin',
'status' => 'active'
];
$permissions = match ($user['role']) {
'admin' => ['read', 'write', 'delete'],
'editor' => ['read', 'write'],
'viewer' => ['read'],
default => [],
};
// nested match expressions
$result = match ($type) {
'number' => match ($value) {
$value > 0 => 'Positive',
$value < 0 => 'Negative',
default => 'Zero',
},
'string' => 'String type',
default => 'Unknown type',
};
// Conditional Logic in Patterns
$score = 85;
$grade = match (true) {
$score >= 90 => 'A',
$score >= 80 => 'B',
$score >= 70 => 'C',
$score >= 60 => 'D',
default => 'F',
};
Advantages Over Switch
- Returns a value - Can be assigned directly to variables
- No fall-through - Prevents accidental bugs
- Strict comparisons - More predictable behavior
- More concise - Less boilerplate code
- Better error handling - Throws UnhandledMatchError for unhandled cases
Important Notes
- Match expressions must be exhaustive or include a default case
- Throws UnhandledMatchError if no pattern matches and no default is provided
- Each arm must be a single expression (use anonymous functions for complex logic)
- Patterns are evaluated in order, first match wins
The match expression is a significant improvement that makes conditional logic more readable, safer, and more expressive in modern PHP code.
Laravel Webpack.mix Asset Compilation AND Performance Optimization
Getting Started with webpack.mix
This is an essential must know for Laravel developers. This tutorial will go through the basics of webpack.mix and preparing live CSS stylesheets and Javascript includes.
Locate webpack.mix.js and the /resources and /public directories. I will define a few ways to specify the files from resources compiled to the live public directory. Check out these 2 examples… they should cover necessary usage for 99% of projects.
Example: Combine multiple files into a single file.
In this example I’ll define a simple way to combine multiple custom javascript files into a single file. Let’s take 4 custom stylesheets and 4 javascript files. We will combine all specified stylesheets from /resources/css into a single stylesheet named /public/css/custom-all.css. Also let’s combine the specified javascript files from /resources/js into a single javascript file named /public/js/custom-all.js
All files that can be edited directly are located in the resources directory. All compiled files will be placed in the public directory where the code can be accessed live.
mix.js('resources/js/app.js', 'public/js')
.vue()
.sass('resources/sass/app.scss', 'public/css');
// Combine all custom JS into one file
mix.scripts([
'resources/js/custom/main.js',
'resources/js/custom/helpers.js',
'resources/js/custom/components/*.js'
], 'public/js/custom-all.js');
// Combine all custom CSS into one file
mix.styles([
'resources/css/custom/main.css',
'resources/css/custom/components/buttons.css',
'resources/css/custom/pages/*.css'
], 'public/css/custom-all.css');
Let’s see how to use things in a blade template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Laravel Application</title>
<!-- Compiled CSS -->
<link href="{{ mix('css/app.css') }}" rel="stylesheet">
<link href="{{ mix('css/custom-all.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<!-- Your application content -->
</div>
<!-- Compiled JavaScript -->
<script src="{{ mix('js/app.js') }}"></script>
<script src="{{ mix('js/custom-all.js') }}"></script>
</body>
</html>
Example: Prepare several files.
This example is very similar to the example above. The only difference is in this example we are generating individual files in the public directory for each file specified from the resources directory.
// Webpack-compiled JS and CSS
mix.js('resources/js/app.js', 'public/js')
.vue({ version: 2 })
.sass('resources/sass/app.scss', 'public/css') // Or .css() if not using Sass
.css('resources/css/app.css', 'public/css');
// Custom JS files (separate from Webpack bundle)
mix.js('resources/js/custom/main.js', 'public/js/custom.js')
.js('resources/js/custom/helpers.js', 'public/js/helpers.js');
// Custom CSS files (separate from Webpack bundle)
mix.css('resources/css/custom/main.css', 'public/css/custom.css')
.css('resources/css/custom/components/buttons.css', 'public/css/components/buttons.css');
Notice in webpack.mix.js the definitions for mix.js and mix.css methods. Each of the javascript files and stylesheets from the resources directory has a corresponding file in the public directory.
Now let’s look at how to use this in a blade template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Laravel Application</title>
<!-- Compiled CSS -->
<link href="{{ mix('css/app.css') }}" rel="stylesheet">
<link href="{{ mix('css/custom.css') }}" rel="stylesheet">
<link href="{{ mix('css/components/buttons.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<!-- Your application content -->
</div>
<!-- Compiled JavaScript -->
<script src="{{ mix('js/app.js') }}"></script>
<script src="{{ mix('js/custom.js') }}"></script>
<script src="{{ mix('js/helpers.js') }}"></script>
</body>
</html>
To generate the public CSS and JS files:
npm install
npm run dev
Defining a Javascript Function
How To Define a JavaScript Function
There are a few different ways to declare a function in Javascript applications. I’ve laid out 4 ways below so choose the method that best fits your use case! Function declarations are great for named functions, whereas arrow functions are excellent for callbacks and shorter functions.
Using Function Declaration
/** Function Declaration */
function functionName(parameters) {
// code to be executed
return value;
}
// Example
function greet(name) {
return "Hello, " + name + "!";
}
console.log(`My name is ${greet("Alice")}`); // "Hello, Alice!"
Using Function Expression
/** Function Expression */
const functionName = function(parameters) {
// code to be executed
return value;
};
// Example
const multiply = function(a, b) {
return a * b;
};
console.log(`5 * 3 = ${multiply(5, 3)}`); // 15
Using Arrow Functions (ES6)
/** Arrow Function (ES6) */
const functionName = (parameters) => {
// code to be executed
return value;
};
// Examples with different syntax
const square = (x) => {
return x * x;
};
console.log(`Square of 4: ${square(4)}`); // 16
// Implicit return (for single expressions)
const squareRoot = x => x ** 0.5;
console.log(`Square Root of 8: ${squareRoot(8)}`);
// Multiple parameters
const add = (a, b) => a + b;
console.log(`2 + 3 = ${add(2, 3)}`); // 5
// No parameters
const title = () => "Math";
console.log(`The page title is "${pageTitle()}"`);
Using the Function Constructor
/** 4. Function Constructor (less common) */
const functionName = new Function("parameters", "function body");
// Example
const divide = new Function("a", "b", "return a / b;");
console.log(divide(10, 2)); // 5
JavaScript Self-Invoked Functions (IIFEs)
What is a self-invoked function? (IIFE)
A self-invoked function, also called an Immediately Invoked Function Expression (IIFE) is a Javascript function expression that is invoked immediately after its declaration. A self-invoked function can be a valuable tool for creating isolated scopes and managing variable privacy in javascript applications.
Key aspects of IIFEs:
- IIFEs execute immediately when defined
- Allows creation of private scopes without polluting global namespace
- Return values can be assigned to variables
- Parameters can be passed to IIFEs
Basic syntax:
(function() {
// code here
})();
// OR arrow functions (ES6+)
(() => {
// code here
})();
Why are IIFEs Necessary?
Immediate Execution with Parameters
// Immediately logs provided data
(function(date, location) {
console.log(`Date: ${date.toDateString()}`);
console.log(`Location: ${location}`);
})(new Date(), 'Seattle');
// Immediately logs:
// Date: Thu Oct 16 2025
// Location: Seattle
Avoiding Global Namespace Pollution
// if multiple scripts use the same variable names
// they won't conflict
(function() {
const restaurant = "Dairy Queen";
console.log(user); // "Dairy Queen"
})();
(function() {
const restaurant = "Burger King";
console.log(user); // "Burger King"
})();
Data Privacy/Encapsulation
// Problem: counter value is vulnerable.
var counter = 0;
function increment() {
return ++counter;
}
// FIX: keeps variables private. counterModule isn't directly accessible
const counterModule = (function() {
let count = 0;
return {
increment: function() {
return ++count;
},
decrement: function() {
return --count;
},
getCount: function() {
return count;
}
};
})();
counterModule.count = 100; // WONT WORK!!
// count is not accessible directly
console.log(counterModule.getCount()); // 0
counterModule.increment();
console.log(counterModule.getCount()); // 1
// OUPTUT: 0 1
Module Pattern Implementation
const User = (function() {
let memory = 0;
function add(a, b) {
return a + b;
}
function store(value) {
memory = value;
}
function recall() {
return memory;
}
// Only expose public methods
return {
add: add,
store: store,
recall: recall
};
})();
console.log(Calculator.add(5, 3)); // 8
Calculator.store(10);
console.log(Calculator.recall()); // 10
// memory is private and inaccessible
Using PHP Class Interface
In PHP, an interface defines a contract or blueprint that any class implementing it must follow.
It specifies method signatures (the names, parameters, and visibility of methods), however does not implement the methods.
A class that implements an interface must define all of the methods declared in the interface.
Interfaces help achieve abstraction and multiple inheritance (since a class can implement multiple interfaces).
Example:
// Define an interface
interface Employee {
public function clockIn(string $message);
}
// Implement the interface in a class
class Engineer implements Employee {
public function clockIn(string $message) {
echo "Engineer Clock In: " . PHP_EOL;
}
}
// Another class implementing the same interface
class Mechanic implements Employee {
public function clockIn(string $message) {
echo "Mechanic Clock In: " . PHP_EOL;
}
}
// Usage
function processTask(Employee $employee) {
$employee->clockIn("Task has been processed!");
}
// You can swap implementations easily
$engineer = new Engineer();
$mechanic = new Mechanic();
processTask($engineer); // Clock In Engineer
processTask($mechanic); // Clock In Mechanic
What interfaces can contain:
- Method declarations (no body/implementation)
- Constants (e.g. const MAX_LIMIT = 100;)
What interfaces cannot contain:
- Properties/variables
- Constructors with implementation
- Method bodies
Example:
interface ExampleInterface {
// Allowed
public function doSomething();
// Allowed
const VERSION = "1.0";
// Not allowed: properties inside interfaces
// public $name; // This will cause an error
}
How To Use PHP Late Static Binding
self:: vs static:: in PHP is all about inheritance and late static binding. So what is late static binding. When building a child class there may be a static property that overrides that same static property on the parent. So when extending this class you will potentially need access to the property on both classes. The way to do this is through late static binding. You can use the self:: and static:: operators to accomplish this.
self::
- Refers to the class where the method is defined.
- Does not consider inheritance overrides.
static::
- Refers to the class that is actually called at runtime.
- This is called late static binding.
- Allows child classes to override static properties/methods and still be respected.
Example: self:: vs static::
class Animal {
public static $type = "Generic Animal";
public static function getTypeUsingSelf() {
return self::$type; // bound to Animal
}
public static function getTypeUsingStatic() {
return static::$type; // late static binding
}
}
class Dog extends Animal {
public static $type = "Dog";
}
// ------------------- USAGE -------------------
echo Dog::getTypeUsingSelf(); // Output: Generic Animal
echo "<br>";
echo Dog::getTypeUsingStatic(); // Output: Dog