Web Development Articles

JavaScript Variable Types (var, const, let)

0 👍
👎 0
 MySQL

There are 3 types of variables commonly used in javascript.  The main difference with the let type it's block scope.  If it's defined inside of a block it can't be accessed outside of the block.   Let's look at each in more detail:

const

Variables defined with const cannot be Redeclared
Variables defined with const cannot be Reassigned
Variables defined with const have Block Scope


// INCORRECT - must be assigned a value when it's declared.
const x;  
x = 1.999;

// INCORRECT - it cannot be reassigned a value
const x = 1.999;

x = 8;  

// IF defined inside of a block it has block scope. Look at example below:
if( somecondition )
{
   const x = 9;
}
// x cannot be access here outside of the "block", curly brackets.
// Below are valid usage of const:
// Example 1:
if( condition )
{
   const x = 8;
   console.log(x);
}

// Example 2:
const x = 8;
if( condition )
{
   console.log(x);
}


Install and Configure ImageMagick for PHP with brew package manager

0 👍
👎 0
 PHP
 ImageMagick

This tutorial will show you step-by-step how to use brew package manager to install ImageMagick and then configure it to work with PHP. 

First check if ImageMagick already exists.  Either command below should do that for you.

 brew info imagemagick


If ImageMagick isn't installed you can simply use the command below to install it.

 brew install imagemagick


Now we need to setup PHP to use the ImageMagick extension.  To do so we can use the pecl package manager.


Check if pkg-config is installed.

 brew info pkg-config

 

If pkg-config isn’t installed run the following command.

 

brew install pkg-config

 

Set a few configurations for pecl.  Run the following 3 commands.

 export PKG_CONFIG_PATH="$(brew --prefix imagemagick)/lib/pkgconfig"

 export CPPFLAGS="-I$(brew --prefix imagemagick)/include/ImageMagick-7"

 export CFLAGS="-DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16"


Install the pecl imagick extension.

 pecl install imagick


Restart PHP with brew.

 brew services restart php


Check that gd and imagick extensions are set up properly.

 php -m | grep -E "gd|imagick"


And that’s it!  You may run into an issue with a non-existing imagick extension.  If you have multiple versions of PHP installed and frequently switch between different versions you will need to install the Imagick extension for each PHP version.

PHP Object Oriented Class Inheritance

0 👍
👎 0
 PHP
 LAMP

PHP class inheritance is a mechanism that allows one class (called the child class or subclass) to inherit properties and methods from another class (called the parent class or superclass).

 

This allows you to reuse code, extend existing functionality, and follow the principle of "Don’t Repeat Yourself (DRY)".


Basics of Inheritance

1. The extends keyword is used in PHP to create inheritance.

2. A child class automatically inherits all the public and protected properties and methods of its parent class.

3. The child class can:

       A. Use the inherited methods and properties directly.

       B. Override methods from the parent class.

       C. Add new methods and properties.

 

Example 1: Basic Inheritance

Here, the Dog class inherits from the Animal class but overrides the speak() method.

 

 // Parent class

 class Animal {

    public $name;

 

    public function __construct($name) {

        $this->name = $name;

    }

 

    public function speak() {

        echo "$this->name makes a sound.<br>";

    }

 }

 

 // Child class

 class Dog extends Animal {

    public function speak() {

        echo "$this->name barks! Woof Woof!<br>";

    }

 }

 

 // Usage

 $animal = new Animal("Generic Animal");

 $animal->speak(); // Output: Generic Animal makes a sound.

 

 $dog = new Dog("Buddy");

 $dog->speak(); // Output: Buddy barks! Woof Woof!

 

 

Example 2: Using parent:: to Call Parent Methods

The Car class overrides the start() method but still uses the parent’s method with parent::start().

 

 class Vehicle {

    public function start() {

        echo "Starting the vehicle...<br>";

    }

 }

 

 class Car extends Vehicle {

    public function start() {

        // Call the parent method first

        parent::start();

        echo "Car engine started!<br>";

    }

 }

 

 $car = new Car();

 $car->start();

 // Output:

 // Starting the vehicle...

 // Car engine started!

 

 

Example 3: Multilevel Inheritance

Human inherits from Animal, and Animal inherits from LivingBeing. So, Human has all methods from both parents.

 

 class LivingBeing {

    public function breathe() {

        echo "Breathing...<br>";

    }

 }

 

 class Animal extends LivingBeing {

    public function eat() {

        echo "Eating...<br>";

    }

 }

 

 class Human extends Animal {

    public function speak() {

        echo "Speaking...<br>";

    }

 }

 

 $person = new Human();

 $person->breathe(); // From LivingBeing

 $person->eat();     // From Animal

 $person->speak();   // From Human

 

 

JavaScript Asynchronous Programming with Promise any()

0 👍
👎 0
 Javascript

Promise.any() is a powerful JavaScript method introduced in ECMAScript 2021 that allows you to handle multiple promises simultaneously. This method returns a single promise that resolves as soon as any one of the input promises fulfills, making it ideal for scenarios where you want the fastest successful result.


Browser and Node.js Compatibility

Node.js: 15.0.0+ (native support)

Chrome: 85+

Firefox: 79+

Safari: 14+

 

For optimal compatibility and performance, we recommend using the latest Node.js LTS version.

 

How Promise.any() Works
Promise.any() takes an iterable of promises and returns a promise that:

 

- Resolves with the value of the first successfully fulfilled promise
- Rejects only if all input promises are rejected

 

Key Characteristics:

 

- Returns the first successful promise (not necessarily the fastest)

- Ignores rejected promises until all promises fail

- Perfect for fallback strategies and redundancy

 

Practical Examples


Example 1: First Successful Promise Wins

 

 // Create promises with different resolve/reject patterns

 const fastPromise = new Promise((resolve, reject) => {

    setTimeout(reject, 100, "fast: rejected");

 });

 

 const mediumPromise = new Promise((resolve, reject) => {

    setTimeout(reject, 99, "medium: rejected");

 });

 

 const slowPromise = new Promise((resolve, reject) => {

    setTimeout(resolve, 50, "slow: resolved");

 });

 

 const veryFastPromise = new Promise((resolve, reject) => {

    setTimeout(() => resolve('very fast: resolved'), 205);

 });

 

 // Use Promise.any() to get the first successful result

 Promise.any([slowPromise, mediumPromise, fastPromise, veryFastPromise])

   .then((result) => {

       console.log("First successful promise:", result);

       // Output: "slow: resolved"

   })

   .catch(error => {

       console.log("All promises failed");

   });

 

 

Example 2: Handling Complete Failure

 

 // All promises will be rejected

 const rejectedFast = new Promise((resolve, reject) => {

    setTimeout(reject, 100, "fast: rejected");

 });

 

 const rejectedMedium = new Promise((resolve, reject) => {

    setTimeout(reject, 99, "medium: rejected");

 });

 

 const rejectedSlow = new Promise((resolve, reject) => {

    setTimeout(reject, 50, "slow: rejected");

 });

 

 const rejectedVeryFast = new Promise((resolve, reject) => {

    setTimeout(() => reject('very fast: rejected'), 205);

 });

 

 Promise.any([rejectedSlow, rejectedMedium, rejectedFast, rejectedVeryFast])

   .then((result) => {

       console.log("Success:", result);

   })

   .catch(error => {

       console.log("Total failures:", error.errors.length);

      

       // Iterate through all rejection reasons

       error.errors.forEach((rejection, index) => {

           console.log(`Failure ${index + 1}:`, rejection);

       });

   });

 

 // Output:

 // Total failures: 4

 // Failure 1: slow: rejected

 // Failure 2: medium: rejected

 // Failure 3: fast: rejected

 // Failure 4: very fast: rejected

 

 

Error Handling Best Practices

Always include a .catch() block when using Promise.any(). Without proper error handling, you might encounter:

 
UnhandledPromiseRejection: This error originated either by throwing inside of

 an async function without a catch block, or by rejecting a promise which was

 not handled with .catch(). The promise rejected with the reason "slow promise

 Rejected".

 

Proper Error Handling Pattern:

 

 Promise.any([promise1, promise2, promise3])

 .then(result => {

    // Handle successful result

    console.log("Success:", result);

 })

 .catch(error => {

    // Handle case where all promises failed

    console.log("All promises rejected");

    console.log("Rejection reasons:", error.errors);

 })

 .finally(() => {

    // Cleanup code that runs regardless of outcome

    console.log("Operation completed");

 });

 

 

Real-World Use Cases

1. Multiple API Endpoints with Fallback

 

 const primaryAPI = fetch('https://primary-api.com/data');

 const backupAPI = fetch('https://backup-api.com/data');

 const cacheAPI = fetch('https://cache-api.com/data');

 

 Promise.any([primaryAPI, backupAPI, cacheAPI])

 .then(response => response.json())

 .then(data => {

    console.log("Data from fastest available source:", data);

 })

 .catch(() => {

    console.log("All data sources unavailable");

 });

 


2. Resource Loading with Redundancy

 

 const cdn1 = loadScript('https://cdn1.com/library.js');

 const cdn2 = loadScript('https://cdn2.com/library.js');

 const cdn3 = loadScript('https://cdn3.com/library.js');

 

 Promise.any([cdn1, cdn2, cdn3])

 .then(() => {

    console.log("Library loaded successfully");

    initializeApp();

 })

 .catch(() => {

    console.error("All CDNs failed - using local fallback");

    loadLocalFallback();

 });

 

 

 

PostgreSQL many-to-many Relationship

0 👍
👎 0
 PostgreSQL

In this example we will look at how to work with a many-to-many relationship.  So first let’s look at a situation where we can leverage a many-to-many relationship.  Imagine we have both Students and Courses.  A student can be enrolled in multiple courses and a course can have multiple students.  This is called a many-to-many relationship and requires what’s called a pivot table.  Although there aren’t any restrictions to the name of a pivot table I will call it “course_student”.  The course_student pivot table will have, at minimum, 2 foreign key fields.  A reference to courses table and a reference to students table.  

 

 

 CREATE TABLE students (

   id INT PRIMARY KEY AUTO_INCREMENT,

   name VARCHAR(100) NOT NULL,

   phone_number VARCHAR(100) UNIQUE NOT NULL,

 

 );

 

 CREATE TABLE courses (

   id INT PRIMARY KEY AUTO_INCREMENT,

   title VARCHAR(100) NOT NULL,

   description TEXT NOT NULL

 );

 

 -- The pivot table has a reference key to each table

 CREATE TABLE course_student (

   student_id INT,

   course_id INT,

   PRIMARY KEY (student_id, course_id),

   FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,

   FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE
);

 

Below are a few useful ways to query this schema. Assuming you are familiar with a LEFT JOIN, these queries specifically use LEFT JOIN for connecting the three tables. courses to course_student to students


# Get all courses that student with id = 2 is enrolled

SELECT c.id course_id, c.title, s.id student_id, s.name

FROM students s

LEFT JOIN course_student cs ON s.id = cs.student_id

LEFT JOIN course c ON c.id = cs.course_id

WHERE s.id = 2;

 

# Get all students enrolled in course with id = 1

 SELECT c.id course_id, c.title, s.id student_id, s.name

 FROM courses c

 LEFT JOIN course_student cs ON c.id = cs.course_id

 LEFT JOIN student s ON s.id = cs.student_id

 WHERE c.id = 1;

 

 

PHP Null Coalescing Operator ??

0 👍
👎 0
 LAMP
The null coalescing operator ?? is used similar to the elvis operator ?:  In the example below the value of $var3 will only be the value of $var2 if $var1 is null.  With no value will $var3 be the value of $var1. 
 
Example 1:

$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 3

PHP Spaceship Operator (<=>)

0 👍
👎 0
 Laravel
 PHP

PHP Spaceship Operator (<=>)

 

The PHP Spaceship Operator (<=>) is a comparison operator that provides a three-way comparison between two values. It's also known as the "combined comparison operator."


How it works:

The operator returns -1, 0, or 1 depending on the condition.
-1 => if the left operand is less than the right operand
0 => if both operands are equal
1 => if the left operand is greater than the right operand

 

Sample Usage:

 

 $a = 1;

 $b = 1;

 $result = $a <=> $b; // result is 0

 

 $b = 2;

 $result = $a <=> $b; // result is -1

 

 $b = 0;

 $result = $a <=> $b; // $result is 1

 

 

Spaceship Operator vs using  if-else:

 

 // using if/else

 if ($a < $b) {

    return -1;

 } elseif ($a > $b) {

    return 1;

 } else {

    return 0;

 }

 

 // using spaceship operator

 return $a <=> $b;

 

 

Benefits:
- Concise: Replaces complex if-else chains
- Readable: Clear intention for comparison
- Consistent: Always returns -1, 0, or 1
- Type-safe: Handles different data types predictably