PHP 8 Programming Tips, Tricks and Best Practices - Doug Bierer - E-Book

PHP 8 Programming Tips, Tricks and Best Practices E-Book

Doug Bierer

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Thanks to its ease of use, PHP is a highly popular programming language used on over 78% of all web servers connected to the Internet. PHP 8 Programming Tips, Tricks, and Best Practices will help you to get up-to-speed with PHP 8 quickly. The book is intended for any PHP developer who wants to become familiar with the cool new features available in PHP 8, and covers areas where developers might experience backward compatibility issues with their existing code after a PHP 8 update. The book thoroughly explores best practices, and highlights ways in which PHP 8 enforces these practices in a much more rigorous fashion than its earlier versions.
You'll start by exploring new PHP 8 features in the area of object-oriented programming (OOP), followed by enhancements at the procedural level. You'll then learn about potential backward compatible breaks and discover best practices for improving performance. The last chapter of the book gives you insights into PHP async, a revolutionary new way of programming, by providing detailed coverage and examples of asynchronous programming using the Swoole extension and Fibers.
By the end of this PHP book, you'll not only have mastered the new features, but you'll also know exactly what to watch out for when migrating older PHP applications to PHP 8.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 564

Veröffentlichungsjahr: 2021

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



PHP 8 Programming Tips, Tricks and Best Practices

A practical guide to PHP 8 features, usage changes, and advanced programming techniques

Doug Bierer

BIRMINGHAM—MUMBAI

PHP 8 Programming Tips, Tricks and Best Practices

Copyright © 2021 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Managers: Richa Tripathi

Publishing Product Manager: Sathyanarayanan Ellapulli

Senior Editor: Storm Mann

Content Development Editor: Nithya Sadanandan

Technical Editor: Pradeep Sahu

Copy Editor: Safis Editing

Project Coordinator: Deeksha Thakkar

Proofreader: Safis Editing

Indexer: Vinayak Purushotham

Production Designer: Jyoti Chauhan

First published: July 2021

Production reference: 1280721

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80107-187-1

www.packt.com

Foreword

I've known Doug Bierer for many years now. It has been my great privilege to work with him on training new PHP developers and helping existing ones to grow their skills. I have even had the distinct privilege of butchering the pronunciation of his name many times. Through the years, though, I've come to respect Doug's ability to take technical concepts and put them in a language that just about anyone can understand. That's why when he wrote and asked me whether I would write the foreword for this book, I was excited to say yes.

Technical training is not easy. Not only does a trainer have to have a thorough understanding of the topic being discussed, but they also have to have the ability to convey ideas and concepts to others in clear language. I've spent a large part of my career struggling with how to best combine these two unrelated skills. Doug makes it look easy and this book is just the latest proof of that. From the language used to the examples given, everything is clearly laid out for you.

PHP 8 is a huge leap forward. Even as we write about PHP 8.0, PHP 8.1 is in the alpha stages of testing, and the tools and concepts embodied in PHP today are as good as they are in any language built for web development. When you add the speed increases that we have enjoyed with each new version for the past few years, you can begin to see why PHP is still a powerhouse of web development.

By purchasing this book, you are taking the first step in being able to harness the power of PHP 8 in your own projects. When you combine the knowledge you will gain from this book and Doug's skill at making the concepts understandable and immediately applicable to your problems, you will have lit the fuse on a rocket that will propel your skills and your career to new heights.

Strap in and hold on – this is going to be a fun ride!

Cal Evans ([email protected])

Senior Consultant, EICC, Inc.

Contributors

About the author

Doug Bierer has been hooked on computers since his first program, written on a DEC PDP-8, in 1971. In his wide-ranging career, he has been a professional contract programmer since 1978, having written applications in BASIC, PL/I, Assembler, FORTH, C, C++, dBase/FoxBase/Clipper, Pascal, Perl, Java, and PHP. He deployed his first website in 1993 while living in San Francisco. He speaks four languages, has traveled extensively, and now resides in Thailand. He also spent some years doing system administration and TCP/IP networking. Some of his technical works include PHP 7 Programming Cookbook and Learning MongoDB 4.x (Packt), as well as Learning PHP and MySQL, Learning PHP Security, and Learning Doctrine (O'Reilly Media).

About the reviewer

Matthew Setter is a highly skilled senior backend software engineer, specializing in PHP and web-based applications, with 20 years' experience. Matthew has worked for small start-ups, in academia, and for Fortune 500 companies.

He has worked on PHP, Go, Bash, TDD and BDD, MySQL, PostgreSQL, MSSQL Server, HTML5, CSS, JavaScript, Docker, Git, Slim, Laminas, Mezzio, Zend Expressive, Zend Framework, Laravel, PHPUnit, Codeception, GoConvey, JUnit, Pico, Nano, Vim, Alpine Linux, Debian, Linux Mint, Ubuntu, Apache, NGINX, ufw, and iptables, with a focus on Laminas/Mezzio and Linux.

Table of Contents

Preface

Section 1: PHP 8 Tips

Chapter 1: Introducing New PHP 8 OOP Features

Technical requirements

Using constructor property promotion

Property promotion syntax

Using property promotion for code reduction

Working with attributes

Overview of PHP comments

PHP DocBlock considerations

Hidden dangers associated with the misuse of DocBlocks

The Attribute class

Attribute syntax

Incorporating match expressions into your program code

Match expression general syntax

Understanding named arguments

Named argument generic syntax

Calling core functions using named arguments

Order independence and documentation

Exploring new data types

Union types

mixed type

The effect of a mixed type on inheritance

Improving code using typed properties

What are typed properties?

Property typing can lead to a reduction in code

Summary

Chapter 2: Learning about PHP 8's Functional Additions

Technical requirements

Working with new PHP 8 operators

Using the variadics operator

Using the nullsafe operator

The concatenation operator has been demoted

Using nested ternary operators

Using arrow functions

Generic syntax

Arrow functions versus anonymous functions

Variable inheritance

Practical example: Using arrow functions

Understanding uniform variable syntax

Defining uniform variable syntax

How does uniform variable syntax affect PHP 8?

Learning new array- and string-handling techniques

Working with array_splice()

Using array_slice()

Detecting string beginning, middle, and end

Securing SQLite databases with the authorizer

Wait a minute... no security?

What's a SQLite authorization callback?

What gets sent to the callback?

Authorizer usage example

Summary

Chapter 3: Taking Advantage of Error-Handling Enhancements

Technical requirements

Understanding PHP 8 error handling

Undefined variable handling

Undefined constant handling

Error-level defaults

Dealing with warnings that are now errors

Promoted warnings in object error handling

Promoted warnings in array handling

Promoted warnings in string handling

Understanding notices promoted to warnings

Non-existent object property access handling

Non-existent offset handling

Misusing resource IDs as array offsets

Ambiguous string offset cast

Uninitialized or non-existent string offsets

Handling the @ error control operator

@ operator usage

@ operator and error_reporting()

Summary

Chapter 4: Making Direct C-Language Calls

Technical requirements

Understanding FFI

Relationship between PHP and the C language

Understanding PHP extensions

Learning where to use FFI

Adopting FFI into PHP

Do not use FFI for speed

Why use the FFI extension?

Examining the FFI class

Working with FFI creational methods

Comparing data using FFI

Using FFI infrastructural methods

Using FFI in an application

Integrating an external C library into a PHP script

Working with PHP callbacks

Summary

Section 2: PHP 8 Tricks

Chapter 5: Discovering Potential OOP Backward-Compatibility Breaks

Technical requirements

Discovering core OOP coding differences

Handling static calls in PHP 8

Dealing with object property handling changes

Working with PHP 8 autoloading

Navigating changes in magic methods

Dealing with constructor changes

Working with changes to __toString()

Taking control of serialization

Understanding PHP serialization

Understanding the __sleep() magic method

Understanding a potential code break in the __sleep() method

Learning about __wakeup()

Introducing the Serializable interface

Examining PHP serializable interface issues

New magic methods to control PHP serialization

Understanding PHP 8 expanded variance support

Understanding covariant returns

Using contravariant parameters

Handling Standard PHP Library (SPL) changes

Understanding changes to SplFileObject

Examining changes to SplHeap

Handling changes in SplDoublyLinkedList

Summary

Chapter 6: Understanding PHP 8 Functional Differences

Technical requirements

Learning key advanced string handling differences

Handling changes to the needle argument

Dealing with v*printf() changes

Working with null length arguments in PHP 8

Examining changes to implode()

Learning about constants usage in PHP 8

Understanding PHP 8 string-to-numeric comparison improvements

Learning about strict and non-strict comparisons

Examining numeric strings

Detecting backward-compatible breaks involving numeric strings

Dealing with inconsistent string-to-numeric comparison results

Understanding comparison changes made in PHP 8

Avoiding problems during a PHP 8 upgrade

Handling differences in arithmetic, bitwise, and concatenation operations

Handling non-scalar data types in arithmetic and bitwise operations

Examining changes in the order of precedence

Taking advantage of locale independence

Understanding the problems associated with locale dependence

Reviewing functions and operations affected by locale independence

Handling arrays in PHP 8

Dealing with negative offsets

Handling curly brace usage changes

Mastering changes in security functions and settings

Understanding changes in disabled functions handling

Learning about changes to the crypt() function

Dealing with changes to password_hash()

Learning about changes to assert()

Summary

Chapter 7: Avoiding Traps When Using PHP 8 Extensions

Technical requirements

Understanding the shift from resources to objects

PHP 8 extension resource-to-object migration

Potential code break involving is_resource()

Advantages of objects over resources

Traversable to IteratorAggregate migration

Learning about changes to XML extensions

Examining XMLWriter extension differences

Working with changes to the SimpleXML extension

Understanding other XML extension changes

Avoiding problems with the updated mbstring extension

Discovering needle-argument differences in mb_str*() functions

Examining changes to mb_ereg*() functions

Dealing with changes to the GD extension

GD extension resource-to-object migration

GD extension compile flag changes

Other GD extension changes

Discovering changes to the Reflection extension

Reflection extension usage

Learning about Reflection extension improvements

Working with other extension gotchas

New database extension operating system library requirements

Reviewing changes to the ZIP extension

Examining PCRE extension changes

Working with Intl extension changes

Understanding cURL extension changes

Reviewing COM extension changes

Examining other extension changes

Summary

Chapter 8: Learning about PHP 8's Deprecated or Removed Functionality

Technical requirements

Discovering what has been removed from the core

Examining functions removed in PHP 8

Discovering other PHP 8 usage changes

Examining core deprecations

Deprecated usage in parameter order

Working with removed functionality in PHP 8 extensions

Discovering mbstring extension changes

Reworking code that uses Reflection*::export()

Discovering other deprecated PHP 8 extension functionality

Changes to the XML-RPC extension

Changes made to the DOM extension

Dealing with deprecated or removed security-related functionality

Examining PHP 8 stream-filter changes

Dealing with custom error-handling changes

Dealing with changes to backtraces

PDO error-handling mode default changed

Examining the track_errors php.ini setting

Summary

Section 3: PHP 8 Best Practices

Chapter 9: Mastering PHP 8 Best Practices

Technical requirements

Discovering method signature changes

Managing magic method signatures

Examining Reflection method signature changes

Dealing with PDO extension signature changes

Dealing with newly defined static methods

Working with the static return type

Extending the use of the ::class constant

Taking advantage of trailing commas

Learning about methods that are no longer required

Working with interfaces and traits

Discovering new DOM extension interfaces

Using new DateTime methods

Understanding PHP 8 trait handling refinements

Dealing with private methods

Controlling anonymous class usage

Understanding changes in namespaces

Discovering differences in tokenization

Using reserved keywords in a namespace

Exposing bad namespace naming practices

Summary

Chapter 10: Improving Performance

Technical requirements

Working with the JIT compiler

Discovering how PHP works without JIT

Enabling the JIT compiler

Configuring the tracing mode

Using the JIT compiler

Debugging with the JIT compiler

Discovering additional JIT compiler settings

Speeding up array handling

Working with SplFixedArray in PHP 8

Implementing stable sort

Understanding stable sorts

Contrasting stable and non-stable sorting

Examining the effect of stable sorting on keys

Handling illegal sort functions

Using weak references to improve efficiency

Taking advantage of weak references

Reviewing the WeakReference class definition

Using weak references

Working with WeakMap

Implementing a container class using SplObjectStorage

Understanding the benefits of WeakMap over SplObjectStorage

Summary

Chapter 11: Migrating Existing PHP Apps to PHP 8

Technical requirements

Understanding development, staging, and production environments

Defining an environment

Learning how to spot BC breaks before a migration

Gaining an overview of BC breaks

Creating a BC break scan configuration file

Developing a BC break scan class

Performing the migration

Step 1 – Review the migration guide

Step 2 – Make sure the current code works

Step 3 – Back up everything

Step 4 – Create a version control branch

Step 5 – Scan for BC breaks

Step 6 – Fix incompatibilities

Step 7 – Repeat steps 5 and 6 as needed

Step 8 – Commit changes to the repository

Step 9 – Test in a simulated virtual environment

Step 10 – Return to step 5 if the test is unsuccessful

Step 11 – Install PHP 8 on the staging environment

Step 12 – Test and clone the staging environment to production

Testing and troubleshooting the migration

Testing and troubleshooting tools

Handling issues with Composer

Working with unit tests

Summary

Chapter 12: Creating PHP 8 Applications Using Asynchronous Programming

Technical requirements

Understanding the PHP async programming model

Developing synchronous programming code

Understanding the asynchronous programming model

Working with async coroutine support

Creating a PHP async application

Using the Swoole extension

Examining the Swoole extension

Installing the Swoole extension

Testing the installation

Examining a sample I/O-intensive application

Using the Swoole extension to improve application performance

Using selected PHP frameworks in async mode

Working with ReactPHP

Implementing PHP async using Amp

Using Mezzio with Swoole

Working with the parallel extension

Learning about PHP 8.1 fibers

Discovering the Fiber class

Using fibers

Examining the effect of fibers on ReactPHP and Swoole

Summary

Why subscribe?

Other Books You May Enjoy

Section 1: PHP 8 Tips

This section introduces cool stuff never seen before, new to PHP 8. The chapters discuss new features, first in Object-Oriented Programming, followed by new things at the functional and extension level. The last chapter in this section covers direct C language prototyping.

In this section, the following chapters are included:

Chapter 1, Introducing New PHP 8 OOP FeaturesChapter 2, Learning about PHP 8's Functional AdditionsChapter 3, Taking Advantage of Error-Handling EnhancementsChapter 4, Making Direct C-Language Calls