Web Development Articles

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

 

PHP $this, self and parent operators

0 👍
👎 0
 Laravel
 PHP

Sometimes different aspects of object oriented programming can be a little confusing if you can’t picture a use case for them.  Three class operators in PHP where usage can be a little confusing at times are $this, self and parent.  In this article I will try to break things down and maybe you can see where you can use this in your code.   Ok so let’s begin.

 

1. $this

- Refers to the current object instance.

- You use $this when you want to access properties or methods of the current object.


Example:

 

 class Animal {

    public $name;

 

    public function setName($name) {

        $this->name = $name;   // "this object’s" name

    }

 

    public function getName() {

        return $this->name;    // returns "this object’s" name

    }

 }

 

 $dog = new Animal();

 $dog->setName("Buddy");

 

 echo $dog->getName(); // Output: Buddy

 

 

2. self

- Refers to the current class itself, not the instance.
- Used for static methods and static properties.
- Does not depend on an object ($this is not available in static context).


Example:

 

 class MathHelper {

    public static $pi = 3.14159;

 

    public static function circleArea($radius) {

        return self::$pi * $radius * $radius; // accessing static property with self

    }

 }

 

 echo MathHelper::circleArea(5); // Output: 78.53975

 

 

3. parent

- Refers to the immediate parent class.
- Used when you want to access a method or constructor from the parent class that is overridden in the child.

Example:

 

 class Animal {

    public function makeSound() {

        return "Some generic animal sound";

    }

 }

 

 class Dog extends Animal {

    public function makeSound() {

        // Call parent method, then add more

        return parent::makeSound() . " and Woof!";

    }

 }

 

 $dog = new Dog();

 echo $dog->makeSound(); // Output: Some generic animal sound and Woof!

 

 

 

Now to summarize:

- $this refers to an instance of the class. It isn’t available in a static context, therefore cannot be used within a static class function.

- The self:: operator refers to the class-level property. It is used in a static context and refers to the actual class itself. 

- The parent:: operator calls the overridden method from the parent class. It’s used in inheritance typically to call an overwritten method on the parent class.

 

Here is a really good example that should help you concieve these concepts and clear up any confusion.

 

 

 class Animal {

    public $name;

    public static $kingdom = "Animalia";

 

    public function __construct($name) {

        $this->name = $name; // instance reference

    }

 

    public function describe() {

        return "I am an animal named {$this->name}.";

    }

 

    public static function getKingdom() {

        return "Kingdom: " . self::$kingdom; // static reference

    }

 }

 

 class Dog extends Animal {

    public function describe() {

        // Use parent to get base description

        $base = parent::describe();

 

        // Add Dog-specific description

        return $base . " I am also a dog that says Woof!";

    }

 

    public function introduce() {

        // `$this` calls instance method

        return $this->describe();

    }

 

    public static function getInfo() {

        // `self` calls static property from this class (or parent if not overridden)

        return "Dogs belong to " . self::$kingdom;

    }

 }

 

 // ------------------- USAGE -------------------

 

 // Create an object

 $dog = new Dog("Buddy");

 

 // $this -> instance reference

 echo $dog->introduce();

 // Output: I am an animal named Buddy. I am also a dog that says Woof!

 

 echo "<br>";

 

 // self -> static reference

 echo Dog::getInfo();

 // Output: Dogs belong to Animalia

 

 echo "<br>";

 

 // parent -> calling parent method inside child

 echo $dog->describe();

 // Output: I am an animal named Buddy. I am also a dog that says Woof!

 

 echo "<br>";

 

 // static method from parent

 echo Animal::getKingdom();

 // Output: Kingdom: Animalia

 




Using PHP Class Interface

0 👍
👎 1
 PHP

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

 }

 

 

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.

Solve Vue.js Component Overload with Parent-Child Patterns

0 👍
👎 0
 Laravel
 VueJS

Has your Vue component become a tangled mess? Too much template markup, too many responsibilities, and decreasing maintainability.  

Well the solution is to use component composition with parent-child relationships that Vue provides.

 

In this tutorial, you'll learn to:

 

1. Refactor effectively breaking up monolithic components into focused children

2. Pass data gracefully using props to send data from parent to child  

3. Handle child events by capturing custom events emitted by child components

4. Maintain clean data flow by establishing predictable communication between components

 

See a real-world example where a parent component delegates UI to a specialized Toolbar child, creating cleaner code and better separation of concerns.

 

Parent Component:

 

 <template>

    <div class="parent-component">

        <h2>Evaluate Product</h2>

      

        <Toolbar :message="message" @evaluate-product="evaluate" />

        <div class="parent-data">

            <p>Total Likes: {{ total.likes }}</p>

            <p>Total Dislikes: {{ total.dislikes }}</p>

            <p v-if="action">Last Action: {{ action }}</p>

        </div>

    </div>

 </template>

 

 <script>

 import Toolbar from './Toolbar.vue';

 

 export default {

  name: 'EvaluateComponent',

  components: {

     Toolbar

  },

  data(){

     return {

        total: {

            likes: 0,

            dislikes: 0

         },

         message: '',

         action: null,

         messageTimeout: null

     }

  },

  methods:{

     evaluate(task) {

         // Clear previous timeout

         if (this.messageTimeout) {

             clearTimeout(this.messageTimeout);

         }

        

         switch(task) {

               case 'like':

                   this.total.likes++;

                   this.message = "Like incremented successfully!";

                   this.action = 'like';

                   break;

               case 'dislike':

                   this.total.dislikes++;

                   this.message = "Dislike incremented successfully!";

                   this.action = 'dislike';

                   break;

         }

        

         // Auto-clear message after 3 seconds

         this.messageTimeout = setTimeout(() => {

             this.message = '';

         }, 3000);

     }

  },

   beforeDestroy() {

     // Clean up timeout when component is destroyed

     if (this.messageTimeout) {

         clearTimeout(this.messageTimeout);

     }

  }

 }

</script>

 



Child Component (Toolbar tag in the parent):

 

<template>

   <div class="child-component">

       <div class="message" v-if="messageSet">{{ message }}</div>

       <button @click="performEvaluate('like')">Like</button>

       <button @click="performEvaluate('dislike')">Dislike</button>

   </div>

</template>

 

<script>

export default {

   props: {

       message: {

           type: String,

           default: ''

       }

   },

   data() {

       return {

           // You can add data properties here if needed

       }

   },

   emits: ['evaluate-product'],

   computed: {

       messageSet() {

           return this.message.length > 0;

       }

   },

   methods: {

       performEvaluate(evaluation) { 

           this.$emit('evaluate-product', evaluation);

       }

   }

}

</script>

 

 

How to use JavaScript Promise catch()

0 👍
👎 0
 Javascript

There are a few ways to take advantage of the Promise catch method.  The catch() method is run when the Promise is rejected or throws an error.  Return value from a Promise is passed forward to the catch() method.  Promises can be chained as well.  It simply forwards the return value from the chained Promise to the catch method if the Promise is rejected or an error is thrown.

 

A basic example of using catch() with a Promise reject:

 

 // using Promise.reject

 let rejectPromise = new Promise(function(resolve, reject){

    reject("promise rejected")

 })

 

 function displayCatch(x) {

    console.log(x)

 }

 

 rejectPromise.catch(x => displayCatch(x))

 

 

A basic example of using catch() by throwing an error from the promise:

 

 // throw an error

 let promiseError = new Promise(function(resolve, reject){

    throw "throw error"

 })

 function displayCatch(x) {

    console.log(x)

 }

 promiseError.catch(x => displayCatch(x));

 

 

Chained promises.  Reject or throw error from chained Promise:

 

 let resolvePromise = new Promise(function(resolve, reject) {

    setTimeout(resolve, 50, "resolved chained");

 })

 

 function resolveDisplay(x) {

    console.log(x)

    throw "throw error from chained Promise"

 }

 

 function displayCatch(x) {

    console.log(x)

 }

 

 resolvePromise.then(x => resolveDisplay(x)).catch(x => displayCatch(x))

 

 

Mastering Promise Chaining with .then() in JavaScript

0 👍
👎 0
 Javascript

Have you ever made an HTTP API request in JavaScript, only to find the data you need is mysteriously unavailable? You're confident the server-side API works, as you've tested it repeatedly. The issue often lies in JavaScript's asynchronous nature.

JavaScript doesn't pause execution to wait for slow operations, like API calls, to complete. Instead, it triggers the request and immediately moves on to the next line of code. By the time your script tries to use the response data, the request may not have finished.

This is where the Promise object becomes essential. A Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Let's explore how to use them effectively.

 

 

1. Basic Promise Handling with .then()

The .then() method is the primary way to interact with a Promise. You can pass it two functions: one to handle a successful resolution and another to handle a rejection.

 

 

 var name = "Mary"

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

    name == "Mary" ? resolve(name) : reject(name)

 });

 

 // promise.then(ifResolved, ifRejected)

 promise.then(

    x => console.log(`name resolved: ${x}`),

    x => console.log(`name rejected: ${x}`)

 ) // expected output "name resolved: Mary"

 

 

 

2. Chaining Multiple .then() Methods

 

Promises are powerful because they can be chained, allowing you to define a sequence of asynchronous steps. Each .then() in the chain receives the result from the previous one. 

 

 

 var name = "Mary"

 

 // initial method provided to the Promise

 const analyzeName = (resolve, reject) => {

    name == "Mary" ? resolve(name) : reject(name)

 }

 

 // method to handle resolved

 const nameResolved = x => {

    console.log(`Name resolved: ${x}`)

    return x

 }

 

 // method to handle rejected

 const nameRejected = x => {

    console.log(`Name rejected: ${x}`)

    return x

 }

 

 // Step 2

 const step2 = x => {

    console.log(`Step 2: ${x}`)

    return x

 }

 

 // Step 3

 const step3 = x => {

    console.log(`Final Step: ${x}`)

    return x

 }

 

const namePromise = new Promise(analyzeName)

namePromise.then(

   x => nameResolved(x), // Expected "Name Resolved: Mary"

   x => nameRejected(x// Expected "Name Rejected Mary"

)

.then(x => step2(x)) // Expected "Step 2: Mary"

.then(x => step3(x)) // Expected "Final Step: Mary"

 

// Name Resolved: Mary

// Step 2: Mary

// Final Step: Mary

 

 

 

Key Takeaway

By using Promises and their .then() method, you gain precise control over the flow of your asynchronous code. This ensures that each step waits for the previous one to complete before executing, which is the fundamental solution to the "missing data" problem in async operations like API calls. For modern, cleaner syntax, consider using async/await, which is built on top of Promises.