Welcome back! Today, we'll master what we learned about backward compatibility in practice. Prepare to apply all the knowledge to practical tasks, but first, let's look at two examples and analyze them.
Task 1: Enhancing a Complex Data Processing Function with Optional Parameters and Default Values
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Let's say that initially, we have a complex data processing class designed to operate on an array of associative arrays, applying a transformation that converts all string values within the array to uppercase. Here's the initial version using PHP:
PHP
<?phpclass DataProcessor{ public function processData(array $items) { $processedItems = []; foreach ($items as $item) { $processedItem = []; foreach ($item as $key => $value) { if (is_string($value)) { $processedItem[$key] = strtoupper($value); } else { $processedItem[$key] = $value; } } $processedItems[] = $processedItem; } for ($i = 0; $i < min(3, count($processedItems)); $i++) { echo "Processed Item: "; print_r($processedItems[$i]); } }}
We intend to expand this functionality, adding capabilities to filter the items based on a condition and allowing for custom transformations. The aim is to retain backward compatibility while introducing these enhancements. Here's the updated approach using optional parameters and closures:
<?phpclass DataProcessor{ public function processData(array $items, callable $condition = null, callable $transform = null) { if ($condition === null) { $condition = function ($item) { return true; }; } $processedItems = []; foreach ($items as $item) { if ($condition($item)) { $processedItem = []; if ($transform !== null) { $processedItem = $transform($item); } else { // Default transformation: Convert string values to uppercase foreach ($item as $key => $value) { $processedItem[$key] = is_string($value) ? strtoupper($value) : $value; } } $processedItems[] = $processedItem; } } for ($i = 0; $i < min(3, count($processedItems)); $i++) { echo "Processed Item: "; print_r($processedItems[$i]); } }}// Usage examples:$data = [ ["name" => "apple", "quantity" => 10], ["name" => "orange", "quantity" => 5]];$processor = new DataProcessor();// Default behavior - convert string values to uppercase$processor->processData($data);// Custom filter - select items with a quantity greater than 5$processor->processData($data, function ($item) { return $item['quantity'] > 5;});// Custom transformation - convert names to uppercase and multiply the quantity by 2$processor->processData($data, null, function ($item) { return [ 'name' => strtoupper($item['name']), 'quantity' => $item['quantity'] * 2 ];});
In this evolved version, we've used optional parameters callable $condition and callable $transform for custom filtering and transformation of items. The default behavior processes all items, converting string values to uppercase, thus maintaining original functionality for existing code paths.
PHP
<?phpclass DataProcessor{ public function processData(array $items, callable $condition = null, callable $transform = null) { if ($condition === null) { $condition = function ($item) { return true; }; } $processedItems = []; foreach ($items as $item) { if ($condition($item)) { $processedItem = []; if ($transform !== null) { $processedItem = $transform($item); } else { // Default transformation: Convert string values to uppercase foreach ($item as $key => $value) { $processedItem[$key] = is_string($value) ? strtoupper($value) : $value; } } $processedItems[] = $processedItem; } } for ($i = 0; $i < min(3, count($processedItems)); $i++) { echo "Processed Item: "; print_r($processedItems[$i]); } }}// Usage examples:$data = [ ["name" => "apple", "quantity" => 10], ["name" => "orange", "quantity" => 5]];$processor = new DataProcessor();// Default behavior - convert string values to uppercase$processor->processData($data);// Custom filter - select items with a quantity greater than 5$processor->processData($data, function ($item) { return $item['quantity'] > 5;});// Custom transformation - convert names to uppercase and multiply the quantity by 2$processor->processData($data, null, function ($item) { return [ 'name' => strtoupper($item['name']), 'quantity' => $item['quantity'] * 2 ];});
Task 2: Using the Adapter Design Pattern for Backward Compatibility
Lesson Summary
Great job! You've delved into backward compatibility while learning how to utilize optional parameters, default values, and the Adapter Design Pattern in PHP. Get ready for some hands-on practice to consolidate these concepts! Remember, practice makes perfect. Happy Coding!
Imagine now that we are building a music player, and recently, market demands have grown. Now, users expect support not just for MP3 and WAV but also for FLAC files within our music player system. This development poses a unique challenge: How do we extend our music player's capabilities to embrace this new format without altering its established interface?
Let's say that we currently have a MusicPlayer class that can only play MP3 files:
PHP
<?phpclass MusicPlayer{ public function play($file) { if (substr($file, -4) === '.mp3') { echo "Playing " . $file . " as mp3.\n"; } else { echo "File format not supported.\n"; } }}
Let's approach this challenge by introducing an adapter that encapsulates different formats and extensions modularly and maintainably:
PHP
<?phpclass MusicPlayerAdapter{ private $player; private $formatAdapters; public function __construct(MusicPlayer $player) { $this->player = $player; $this->formatAdapters = [ '.wav' => function($file) { $convertedFile = str_replace('.wav', '.mp3', $file); echo "Converting $file to $convertedFile and playing as mp3...\n"; $this->player->play($convertedFile); }, '.flac' => function($file) { $convertedFile = str_replace('.flac', '.mp3', $file); echo "Converting $file to $convertedFile and playing as mp3...\n"; $this->player->play($convertedFile); } ]; } public function play($file) { $fileExtension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); $fileExtension = '.' . $fileExtension; if (isset($this->formatAdapters[$fileExtension])) { $this->formatAdapters[$fileExtension]($file); } else { $this->player->play($file); } }}// Upgraded music player with enhanced functionality through the composite adapter$legacyPlayer = new MusicPlayer();$enhancedPlayer = new MusicPlayerAdapter($legacyPlayer);$enhancedPlayer->play("song.mp3"); // Supported directly$enhancedPlayer->play("song.wav"); // Supported through adaptation$enhancedPlayer->play("song.flac"); // Newly supported through additional adaptation
This adaptation ensures that we can extend the MusicPlayer to include support for additional file formats without altering its original code. The MusicPlayerAdapter acts as a unified interface to the legacy MusicPlayer, handling formats by determining the appropriate strategy based on the file type.