В материале использованы примеры из статей: раз, два.

Санитизация ввода

PHP
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$age = filter_var($_POST['age'], FILTER_SANITIZE_NUMBER_INT);

Стрелочные функции

PHP
// Before
$numbers = array_map(function($n) {
    return $n * 2;
}, $numbers);

// After (PHP 7.4+)
$numbers = array_map(fn($n) => $n * 2, $numbers);

Выражение match

PHP
$result = match ($status) {
    200, 300 => 'success',
    400 => 'bad request',
    500 => 'server error',
    default => 'unknown status',
};

Генераторы для больших массивов

PHP
function readLargeFile($filename) {
    $handle = fopen($filename, 'r');
    while (!feof($handle)) {
        yield trim(fgets($handle));
    }
    fclose($handle);
}

API Rate Limiting

PHP
// Using Redis for rate limiting
public function rateLimit($key, $limit = 60) {
    $redis = Redis::connection();
    $count = $redis->incr($key);
    $redis->expire($key, 60);
    
    return $count <= $limit;
}

Асинхронное программирование

PHP
$fiber = new Fiber(function(): void {
    $result = heavyOperation();
    Fiber::suspend($result);
    cleanup();
});

$fiber->start();
$result = $fiber->resume();

Кэширование

PHP
// Using Redis for caching
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$cachedData = $redis->get('key');
if (!$cachedData) {
    $data = computeExpensiveOperation();
    $redis->set('key', $data, 3600); // Cache for 1 hour
}

Продвинутое кэширование

PHP
class CacheManager {
    private Redis $redis;
    private array $localCache = [];
    
    public function get(string $key, callable $callback, int $ttl = 3600): mixed {
        // Check local cache first
        if (isset($this->localCache[$key])) {
            return $this->localCache[$key];
        }
        
        // Check Redis cache
        $value = $this->redis->get($key);
        if ($value !== false) {
            $this->localCache[$key] = unserialize($value);
            return $this->localCache[$key];
        }
        
        // Generate and cache value
        $value = $callback();
        $this->redis->setex($key, $ttl, serialize($value));
        $this->localCache[$key] = $value;
        
        return $value;
    }
}

Продвинутые потоки

PHP
class StreamHandler {
    public function handleStream(string $url): void {
        $context = stream_context_create([
            'http' => [
                'method' => 'GET',
                'header' => [
                    'User-Agent: PHP Stream Handler',
                    'Accept: application/json'
                ]
            ]
        ]);
        
        $stream = fopen($url, 'r', false, $context);
        
        if ($stream) {
            stream_set_timeout($stream, 30);
            stream_set_chunk_size($stream, 8192);
            
            while (!feof($stream)) {
                $chunk = fread($stream, 8192);
                // Process chunk
            }
            
            fclose($stream);
        }
    }
    
    public function createCustomStream(): void {
        stream_wrapper_register('custom', CustomStreamWrapper::class);
        // Now you can use custom:// protocol
    }
}

Продвинутое использование SPL

PHP
class SPLDemo {
    public function demonstrateDataStructures(): void {
        // Using SplFixedArray for better memory usage
        $fixedArray = new SplFixedArray(5);
        $fixedArray[0] = "First";
        
        // Priority Queue implementation
        $queue = new SplPriorityQueue();
        $queue->insert('high', 3);
        $queue->insert('medium', 2);
        $queue->insert('low', 1);
        
        // Using SplObjectStorage for object-based storage
        $storage = new SplObjectStorage();
        $obj1 = new stdClass();
        $storage->attach($obj1, 'metadata');
        
        // Directory handling with SPL
        $directory = new RecursiveDirectoryIterator('path/to/dir');
        $iterator = new RecursiveIteratorIterator($directory);
        foreach ($iterator as $file) {
            if ($file->isFile()) {
                // Process file
            }
        }
    }
    
    public function useCustomIterator(): void {
        class MyIterator implements Iterator {
            private int $position = 0;
            private array $array = [];
            
            public function __construct(array $array) {
                $this->array = $array;
            }
            
            public function rewind(): void {
                $this->position = 0;
            }
            
            public function current(): mixed {
                return $this->array[$this->position];
            }
            
            public function key(): mixed {
                return $this->position;
            }
            
            public function next(): void {
                ++$this->position;
            }
            
            public function valid(): bool {
                return isset($this->array[$this->position]);
            }
        }
    }
}