PHP Cookbook: Modern Code Solutions for Professional Developers / Книга рецептов PHP: Современные решения разработки кода для профессиональных разработчиков
Год издания: 2023
Автор: Mann E. A. / Манн Э. А.
Издательство: O’Reilly Media
ISBN: 978-1-098-12132-7
Язык: Английский
Формат: PDF, EPUB, MOBI
Качество: Издательский макет или текст (eBook)
Интерактивное оглавление: Да
Количество страниц: 434
Описание: If you’re a PHP developer looking for proven solutions to common problems, this cookbook provides code recipes to help you resolve numerous scenarios. By leveraging modern versions of PHP through version 8.2, these self-contained recipes provide fully realized solutions that can help you solve similar problems in your day-to-day work.
Whether you’re new to development or merely new to PHP, these recipes will help you unpack the most powerful features of this programming language. Author Eric Mann, a regular contributor to php[architect] magazine, frequently makes presentations on software architecture and has built scalable projects for startups and Fortune 500 companies alike.
Learn the type system of modern PHP
Build efficient applications composed of functions and objects
Understand key concepts such as encryption, error handling, debugging, and performance tuning
Explore the PHP package/extension ecosystem
Learn how to build basic web and basic command-line applications
Work securely with files on a machine, both encrypted and in plain text
Если вы разработчик PHP, ищущий проверенные решения распространенных проблем, в этой книге приведены рецепты кода, которые помогут вам справиться с многочисленными сценариями. Используя современные версии PHP, начиная с версии 8.2, эти автономные рецепты предоставляют полностью реализованные решения, которые могут помочь вам решать аналогичные проблемы в вашей повседневной работе.
Независимо от того, новичок ли вы в разработке или просто новичок в PHP, эти рецепты помогут вам распаковать самые мощные возможности этого языка программирования. Автор Эрик Манн, постоянный автор журнала php[architect], часто выступает с презентациями по архитектуре программного обеспечения и создавал масштабируемые проекты как для стартапов, так и для компаний из списка Fortune 500.
Изучите систему типов современного PHP
Создавайте эффективные приложения, состоящие из функций и объектов
Понимать ключевые понятия, такие как шифрование, обработка ошибок, отладка и настройка производительности
Изучите экосистему пакетов/расширений PHP
Узнайте, как создавать базовые веб-приложения и приложения командной строки
Безопасная работа с файлами на компьютере, как зашифрованными, так и в виде обычного текста
Оглавление
Preface xi
1. Variables 1
1.1 Defining Constants 3
1.2 Creating Variable Variables 4
1.3 Swapping Variables in Place 7
2. Operators 11
2.1 Using a Ternary Operator Instead of an If-Else Block 15
2.2 Coalescing Potentially Null Values 17
2.3 Comparing Identical Values 18
2.4 Using the Spaceship Operator to Sort Values 20
2.5 Suppressing Diagnostic Errors with an Operator 23
2.6 Comparing Bits Within Integers 24
3. Functions 29
3.1 Accessing Function Parameters 31
3.2 Setting a Function’s Default Parameters 33
3.3 Using Named Function Parameters 35
3.4 Enforcing Function Argument and Return Typing 37
3.5 Defining a Function with a Variable Number of Arguments 40
3.6 Returning More Than One Value 42
3.7 Accessing Global Variables from Within a Function 44
3.8 Managing State Within a Function Across Multiple Invocations 47
3.9 Defining Dynamic Functions 50
3.10 Passing Functions as Parameters to Other Functions 51
3.11 Using Concise Function Definitions (Arrow Functions) 54
3.12 Creating a Function with No Return Value 56
3.13 Creating a Function That Does Not Return 58
4. Strings 61
4.1 Accessing Substrings Within a Larger String 64
4.2 Extracting One String from Within Another 65
4.3 Replacing Part of a String 67
4.4 Processing a String One Byte at a Time 70
4.5 Generating Random Strings 72
4.6 Interpolating Variables Within a String 73
4.7 Concatenating Multiple Strings Together 75
4.8 Managing Binary Data Stored in Strings 77
5. Numbers 81
5.1 Validating a Number Within a Variable 82
5.2 Comparing Floating-Point Numbers 84
5.3 Rounding Floating-Point Numbers 86
5.4 Generating Truly Random Numbers 88
5.5 Generating Predictable Random Numbers 89
5.6 Generating Weighted Random Numbers 91
5.7 Calculating Logarithms 94
5.8 Calculating Exponents 94
5.9 Formatting Numbers as Strings 96
5.10 Handling Very Large or Very Small Numbers 97
5.11 Converting Numbers Between Numerical Bases 99
6. Dates and Times 101
6.1 Finding the Current Date and Time 102
6.2 Formatting Dates and Times 104
6.3 Converting Dates and Times to Unix Timestamps 107
6.4 Converting from Unix Timestamps to Date and Time Parts 109
6.5 Computing the Difference Between Two Dates 110
6.6 Parsing Dates and Times from Arbitrary Strings 111
6.7 Validating a Date 114
6.8 Adding to or Subtracting from a Date 115
6.9 Calculating Times Across Time Zones 119
7. Arrays 123
7.1 Associating Multiple Elements per Key in an Array 125
7.2 Initializing an Array with a Range of Numbers 127
7.3 Iterating Through Items in an Array 129
7.4 Deleting Elements from Associative and Numeric Arrays 131
7.5 Changing the Size of an Array 135
7.6 Appending One Array to Another 137
7.7 Creating an Array from a Fragment of an Existing Array 140
7.8 Converting Between Arrays and Strings 143
7.9 Reversing an Array 146
7.10 Sorting an Array 147
7.11 Sorting an Array Based on a Function 150
7.12 Randomizing the Elements in an Array 152
7.13 Applying a Function to Every Element of an Array 153
7.14 Reducing an Array to a Single Value 156
7.15 Iterating over Infinite or Very Large/Expensive Arrays 157
8. Classes and Objects 161
8.1 Instantiating Objects from Custom Classes 168
8.2 Constructing Objects to Define Defaults 170
8.3 Defining Read-Only Properties in a Class 172
8.4 Deconstructing Objects to Clean Up After the Object Is No Longer Needed 175
8.5 Using Magic Methods to Provide Dynamic Properties 177
8.6 Extending Classes to Define Additional Functionality 179
8.7 Forcing Classes to Exhibit Specific Behavior 181
8.8 Creating Abstract Base Classes 186
8.9 Preventing Changes to Classes and Methods 188
8.10 Cloning Objects 192
8.11 Defining Static Properties and Methods 196
8.12 Introspecting Private Properties or Methods Within an Object 199
8.13 Reusing Arbitrary Code Between Classes 201
9. Security and Encryption 205
9.1 Filtering, Validating, and Sanitizing User Input 212
9.2 Keeping Sensitive Credentials Out of Application Code 216
9.3 Hashing and Validating Passwords 218
9.4 Encrypting and Decrypting Data 221
9.5 Storing Encrypted Data in a File 227
9.6 Cryptographically Signing a Message to Be Sent to Another Application 231
9.7 Verifying a Cryptographic Signature 233
10. File Handling 235
10.1 Creating or Opening a Local File 236
10.2 Reading a File into a String 238
10.3 Reading a Specific Slice of a File 239
10.4 Modifying a File in Place 241
10.5 Writing to Many Files Simultaneously 242
10.6 Locking a File to Prevent Access or Modification by Another Process 244
11. Streams 247
11.1 Streaming Data to/from a Temporary File 251
11.2 Reading from the PHP Input Stream 253
11.3 Writing to the PHP Output Stream 256
11.4 Reading from One Stream and Writing to Another 258
11.5 Composing Different Stream Handlers Together 260
11.6 Writing a Custom Stream Wrapper 264
12. Error Handling 269
12.1 Finding and Fixing Parse Errors 269
12.2 Creating and Handling Custom Exceptions 271
12.3 Hiding Error Messages from End Users 273
12.4 Using a Custom Error Handler 276
12.5 Logging Errors to an External Stream 277
13. Debugging and Testing 279
13.1 Using a Debugger Extension 281
13.2 Writing a Unit Test 283
13.3 Automating Unit Tests 288
13.4 Using Static Code Analysis 291
13.5 Logging Debugging Information 292
13.6 Dumping Variable Contents as Strings 296
13.7 Using the Built-in Web Server to Quickly Run an Application 299
13.8 Using Unit Tests to Detect Regressions in a Version-Controlled Project with git-bisect 301
14. Performance Tuning 307
14.1 Timing Function Execution 310
14.2 Benchmarking the Performance of an Application 314
14.3 Accelerating an Application with an Opcode Cache 320
15. Packages and Extensions 325
15.1 Defining a Composer Project 327
15.2 Finding Composer Packages 330
15.3 Installing and Updating Composer Packages 332
15.4 Installing Native PHP Extensions 335
16. Databases 339
16.1 Relational Databases 339
16.2 Key-Value Stores 340
16.3 Graph Databases 341
16.4 Document Databases 342
16.5 Connecting to an SQLite Database 342
16.6 Using PDO to Connect to an External Database Provider 344
16.7 Sanitizing User Input for a Database Query 349
16.8 Mocking Data for Integration Testing with a Database 351
16.9 Querying an SQL Database with the Eloquent ORM 356
17. Asynchronous PHP 361
17.1 Fetching Data from Remote APIs Asynchronously 367
17.2 Waiting on the Results of Multiple Asynchronous Operations 369
17.3 Interrupting One Operation to Run Another 371
17.4 Running Code in a Separate Thread 374
17.5 Sending and Receiving Messages Between Separate Threads 379
17.6 Using a Fiber to Manage the Contents from a Stream 383
18. PHP Command Line 389
18.1 Parsing Program Arguments 390
18.2 Reading Interactive User Input 393
18.3 Colorizing Console Output 395
18.4 Creating a Command-Line Application with Symfony Console 396
18.5 Using PHP’s Native Read-Eval-Print-Loop 400
Index 403