Introduction

Welcome to our lesson on mastering data aggregation and data streams with PHP. In this lesson, you'll learn to build a basic sales records aggregator using PHP's associative arrays and classes. Then, we'll extend its functionality to handle more complex operations such as filtering, data aggregation, and formatting. By the end of this session, you'll be proficient in managing and formatting data streams efficiently in PHP.

Starter Task Methods and Their Definitions

To get started, we'll create a simple sales record aggregator in PHP. Here are the methods we'll focus on:

  • public function addSale(string $saleId, float $amount, string $date): void; — Adds or updates a sale record with a unique identifier saleId, amount, and a date in the format "YYYY-MM-DD".

  • public function getSale(string $saleId): ?float; — Retrieves the sale amount associated with the saleId. If the sale does not exist, it returns null.

  • public function deleteSale(string $saleId): bool; — Deletes the sale record with the given saleId. Returns true if the sale was deleted and false if the sale does not exist.

Are these methods clear so far? Great! Let's now look at how we would implement them.

Starter Task Implementation

Here is the complete code for the starter task:

Explanation:

  • The $sales array stores sale records with saleId as the key and an associative array of amount and date as the value.
  • addSale adds a new sale or updates an existing sale ID.
  • getSale retrieves the amount for a given sale ID or returns null if the sale does not exist.
  • deleteSale removes the sale record for the given sale ID or returns false if the sale does not exist.

Now that we have our basic aggregator, let's extend it to include more advanced functionalities.

Step 1: Implementing the 'Aggregate Sales' Method

We'll create the aggregateSales method:

This method iterates through the sales and sums those that exceed the minAmount.

Step 2: Implementing the 'Format Sales' Method

Next, we create the formatSales method to output data in plain text format.

In this method, we use PHP's simple string concatenation to build the output string for formatted data.

Step 3: Implementing the 'Get Sales in Date Range' Method

Let's implement getSalesInDateRange, which relies on PHP's DateTime objects for date comparison.

In this method, PHP's DateTime class is used to compare dates and ensure accurate filtering of sales records.

Lesson Summary

Congratulations! You've extended a basic PHP sales aggregator to an advanced aggregator, capable of filtering, aggregating, and formatting data using PHP's built-in structures and functions. These skills are crucial for efficiently managing data streams, especially with varying datasets in PHP. Feel free to experiment with similar challenges to reinforce your understanding. Well done!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal