The Art of Modern PHP 8 - Joseph Edmonds - E-Book

The Art of Modern PHP 8 E-Book

Joseph Edmonds

0,0
31,19 €

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

Mehr erfahren.
Beschreibung

PHP has come a long way since its introduction. While the language has evolved with PHP 8, there are still a lot of websites running on a version of PHP that is no longer supported. If you are a PHP developer working with legacy PHP systems and want to discover the tenants of modern PHP, this is the book for you.
The Art of Modern PHP 8 walks you through the latest PHP features and language concepts. The book helps you upgrade your knowledge of PHP programming and practices. Starting with object-oriented programming (OOP) in PHP and related language features, you'll work through modern programming techniques such as inheritance, understand how it contrasts with composition, and finally look at more advanced language features. You'll learn about the MVC pattern by developing your own MVC system and advance to understanding what a DI container does by building a toy DI container. The book gives you an overview of Composer and how to use it to create reusable PHP packages. You’ll also find techniques for deploying these packages to package libraries for other developers to explore.
By the end of this PHP book, you'll have equipped yourself with modern server-side programming techniques using the latest versions of PHP.

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

EPUB
MOBI

Seitenzahl: 384

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.



The Art of Modern PHP 8

Learn how to write modern, performant, and enterprise-ready code with the latest PHP features and practices

Joseph Edmonds

BIRMINGHAM—MUMBAI

The Art of Modern PHP 8

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.

Associate Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Pavan Ramchandani

Senior Editor: Sofi Rogers

Content Development Editor: Feza Shaikh

Technical Editor: Saurabh Kadave

Copy Editor: Safis Editing

Project Coordinator: Manthan Patel

Proofreader: Safis Editing

Indexer: Subalakshmi Govindhan

Production Designer: Sinhayna Bais

First published: September 2021

Production reference: 1240921

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

978-1-80056-615-6

www.packt.com

To my family, who have always supported me.

– Joseph Edmonds

Foreword

I've known Joseph as a member of the local-to-me PHP community here in Yorkshire, England, for what feels like a very long time. Over the years I taught PHP to him and then to the staff he worked hard to train up – and so I was delighted to hear about this book and to be invited to write a few words to introduce it. I know your author as a thoughtful and technical contributor and someone who works to raise his own game and also to share his skills and knowledge with others.

Taking care to learn and keep learning is such an important thing for anyone working in a technical career, or even as a hobby. The only constant is ... that nothing is constant! We always need to be learning, exploring, and developing ourselves. Perhaps you will consume this book quickly, wolfing down the information as fast as you can. Or maybe your style is more to dip in, to make space for a little more knowledge when you are ready to learn and apply something new. Some of you probably won't read the whole book, looking to graze on the parts that interest you or where you are keen to update your knowledge. All of you are investing in yourself, your future, and taking the care to learn.

In this Internet Age, the wealth of information available is incredible. And sometimes? It's too much to swim through it all and somehow fish out just the nugget we need. Reading a well-structured book means taking a prescribed route through complex information and receiving a curated collection of applicable wisdom. If there's something you want to know more about, then you can dive into the uncharted waters of other resources – and you already have a good idea of what you are looking for and how it fits the bigger picture.

Thinking about keeping up to date is one of the big preoccupations of our technical lives. With PHP, there's a disconnect where the language is perceived by others as being old-fashioned, and yet in recent years, it has changed beyond recognition and continues to grow and evolve. I have yet to see data indicating a meaningful decline in PHP's popularity, and rarely hear negativity from anyone with real recent experience of modern versions of PHP. Joseph has been working with PHP throughout these changes and covers the topics you need to understand to make the best use of PHP 8 and beyond.

As a fellow author, who once passed on her knowledge to other PHP people, I am so proud to be part of this thriving tech community still sharing the knowledge and paying it forward. I hope this book will boost your PHP activities, bringing solid theory to things you already know, as well as shining a light onto things you may not have encountered yet. And one day? Who knows, maybe it will be you that writes the next blog post, article, or even book to help inform and inspire the next generation.

Lorna Mitchell

Developer Advocate, Engineer, Author and Speaker

Contributors

About the author

Joseph Edmonds is a business owner, developer, and author. He is a Zend Certified Engineer, among his other credentials.

He's been a part of the e-commerce, tech, and PHP development worlds since the dawn of the millennium. He witnessed the exploding growth of e-commerce from the early days, helping several companies advance and expand their operations. During this time, he has had the pleasure of seeing PHP grow from a fairly amateur language, punching way above its weight, into a modern and highly performant language for serious enterprise projects.

Responding to a growing demand for highly specialized PHP development services, he launched Edmonds Commerce (https://edmondscommerce.co.uk) in 2007. As an independent agency, Edmonds Commerce provides highly specialist PHP development services to businesses that use open source PHP, and predominantly Magento, as the backbone of their online systems, solving even the most complex and unique PHP development challenges.

As a way to offer a high-level, interrelated service to businesses who want to accelerate their growth, he started an exciting new venture in 2020. LTS (Long Term Support Ltd.) provides expert help in recruitment, training, DevOps and infrastructure, consultancy, and development.

You can see his personal website and contact him via:

https://joseph.edmonds.contact

Feel free to get in touch!

Many people have helped me get where I am today and I can't thank everyone. Specifically, I would like to thank Zach Stein, who has been a great help as a technical reviewer and has given me lots of useful feedback. I'd also like to thank the people who stepped up to join my small Slack-based focus group and helped me bounce ideas and get some general feedback. My wife, Nolwenn, deserves special thanks for putting up with my late-night writing sessions and generally putting up with me for many years. Ross Mitchell and Daniel Callaghan, who are the lead developers of Edmonds Commerce, deserve a special thank you for working with me for years and bringing many useful ideas and practices that have no doubt made their way into these pages. And finally, my thanks to Sofi, Pavan, and the rest of the team at Packt who managed to accommodate my unorthodox ways and allowed the book to be created as closely to my vision as possible. I even managed to avoid using MS Word :)

About the reviewer

Zach Stein is a developer who has been using PHP for 18 years and has been a professional developer for 15 years, with a focus on enterprise application development. In that time he has been involved in building numerous types of applications, ranging from e-commerce to healthcare, to social networking using a variety of frameworks, such as Laravel, Symfony, Magento, and Zend. Zach has a passion for design patterns and the sometimes-tedious task of refactoring code. In addition to his passion for software, Zach loves building teams and helping other developers hone their craft.

He holds a master of science degree from La Salle University in computer information science.

In his spare time, you can find Zach on the golf course or in the woodshop making furniture.

I'd like to thank my wife, Jill, and my three cats, Rory, River, and Lilly, for allowing me to spend the time reading and testing the code in this book. I'd also like to thank Joe, without whom this book would not exist, and I hope readers of The Art of Modern PHP 8 find it at least as informative, if not more so, as I did.

Table of Contents

Preface

Section 1 – PHP 8 OOP

Chapter 1: Object-Oriented PHP

What is OOP?

Understanding the phrase

OOP alternatives

Learning object-oriented PHP

PHP OOP basics

Classes

Interfaces

Namespaces

Summary

Chapter 2: Inheritance and Composition, Encapsulation and Visibility, Interfaces and Concretions

Encapsulation and visibility

Private, protected, and public

Inheritance–the classical parent, child, and "is a" style

Constructor promotion

Composition–the modern, flexible "has a" style

Interfaces instead of abstract classes

Summary

Chapter 3: Advanced OOP Features

SPL – the Standard PHP Library

Data structures

Iterators

Exceptions and error handling

Yoda and Pokemon exception handling

Exception and error handling best practices

Meta-programming with reflection and attributes

Reflection

Attributes

Summary

Section 2 – PHP Types

Chapter 4: Scalar, Arrays, and Special Types

Scalar types

Strings

Ints

Floats

Bools

Type juggling

Type and value comparison

Arrays and iterables

Arrays

Iterables

DocBlock types

Nullable, void, and uninitialized

Null and nullable

Void

Uninitialized

Resources

Summary

Chapter 5: Object Types, Interfaces, and Unions

Object type inheritance

Object comparison

Passing objects by reference

Making new objects

Summary

Chapter 6: Parameter, Property, and Return Types

Coercive and strict modes

Covariance and contravariance

Contravariance – that is, allowing less specific parameter types than the parent

Covariance – that is, allowing more specific return types than the parent

Remembering the rules

Summary

Section 3 – Clean PHP 8 Patterns and StyleChapter 7: Design Patterns and Clean Code

Clean Code Acronyms (CCA)

DRY

KICK

Design patterns

Creational patterns

Structural patterns

Behavioral patterns

Architectural patterns

Summary

Chapter 8: Model, View, Controller (MVC) Example

Model, View, Controller – MVC

Controller

Front controller

Model

Entity pattern

Universally unique identifier (UUID)

Persistence and ORM

Singleton anti-pattern

Repository pattern

Collection pattern

View

It lives

Summary

Chapter 9: Dependency Injection Example

Inversion of control container

Dependency injection and the service locator

The service locator anti-pattern

Summary

Section 4 – PHP 8 Composer Package Management (and PHP 8.1)

Chapter 10: Composer For Dependencies

What is Composer?

What are dependencies?

Dependency resolution

But wait, there's more

In a nutshell, it's awesome

Get it installed!

Composer autoloader

Old-fashioned versus autoloaded

A real-world, old-fashioned example

Extra points

Autoloading in PHP

Configuring Composer autoloader

Using Composer to require packages

Finding dependencies

Initialization of composer.json

What is a vendor?

Minimum stability

Package type

License

So far, so good

Installing monolog

Ignore the vendor directory in your VCS

The composer.lock file

Adding extra dependencies

Version constraints

SemVer in a nutshell

Caret (^) Version Range

Tilde (~) Version Range

Exact version

Version range

Multiple acceptable versions

Full documentation

Dev and prod dependencies

Requiring dev dependencies

Installing without dev dependencies

Summary

Chapter 11: Creating Your Own Composer Package

Writing composer.json

Name

Description

Keywords

License

Using source folders and namespaces

Executable Binaries Configured under bin

Extensionless files

Executable permissions

Finding an autoloader

Using versions and tagging

Creating a Git tag

SemVer

Stable and development versions

Private Git repos as Composer dependencies

Publishing on Packagist

Things to check before you publish

Submitting your package to Packagist

Created

If you were just testing, delete it

Summary

Section 5 – Bonus Section - PHP 8.1

Chapter 12: The Awesomeness That Is 8.1

Enumerations

Basic and backed enums

Creating enum instances

Not just classes with cases

Readonly properties

Readonly gotchas

Intersection types

Never return type

Final constants

Summary – end of the book

Other Books You May Enjoy

Preface


I've had the great pleasure of seeing PHP grow; from a somewhat amateur, and often mocked, language that exploded in popularity, punching way above its weight and powering huge swathes of the burgeoning web into a modern and highly performant language that is often used to power large-scale enterprise systems.

With the release of PHP 8, and the upcoming (at the time of writing) release of PHP 8.1, we can really see a bright future for PHP.

You will first read about object-oriented programming (OOP) in PHP, starting with the basics and then going on to more advanced topics. You will work through modern programming techniques, such as inheritance, contrasting this with composition, and finally looking at more advanced language features. You will learn about the MVC pattern by building your own toy MVC system. In addition to this, you'll explore what a dependency injection (DI) container does by building a toy DI container. Later chapters will give you an overview of Composer and will explain how to create reusable PHP packages with it. You'll also find techniques to deploy these packages effectively so that other developers can use them.

By the end of this PHP book, you will have gained a rounded understanding of some of the fundamentals of modern PHP and will have the grounding you need to be able to update your code.

Who this book is for

As PHP has such a long history, it also means that there are many developers out there who are still standing with at least one foot in the past and are missing out on the bright and beautiful future of modern PHP. This book is for you, most of all.

The book is for existing PHP developers and CTO-level professionals who are working with PHP technologies, including legacy PHP, in production. The book assumes a reasonable level of knowledge of PHP programming and may require you to hit the PHP documentation to fill in gaps in your knowledge as they come up.

What this book covers

Chapter 1, Object-Oriented PHP, includes a quick overview of what OOP means and how it contrasts with functional and procedural styles. We review some popular OOP PHP projects that you might want to have a look at and then we go over the basics of classes, objects, interfaces, and namespaces.

Chapter 2, Inheritance and Composition, Encapsulation and Visibility, Interfaces and Concretions, following the theme of looking at OOP, explores inheritance in some detail and then contrasts this with a more modern approach of using composition. You are encouraged to download the code in order to get the most out of this chapter.

Chapter 3, Advanced OOP Features, the third and final chapter in Section 1, continues looking at OOP, and this time we're looking at the SPL (Standard PHP Library), exceptions and error handling, and finally meta-programming with reflection and attributes.

Chapter 4, Scalar, Arrays, and Special Types, explains that since PHP 7, types have become a major feature in modern PHP. This chapter looks at the simpler types, including scalars, arrays, and iterables, and then the "nothing" types of null, void, and uninitialized.

Chapter 5, Object Types, Interfaces, and Unions, continues looking at types, but our focus shifts onto looking at exactly how the type system works when dealing with classes and interfaces.

Chapter 6, Parameter, Property, and Return Types, the final chapter in Section 2, looks at how types can be enforced strictly and examines their usage as parameter, property, and return types. We conclude by looking at covariance and contravariance and confirm how this works in PHP 8.

Chapter 7, Design Patterns and Clean Code, moves on from learning about the language itself and starts to look at ways we write it. We look at some clean coding practices and then have an overview of design patterns that are tried and tested approaches to common requirements.

Chapter 8, Model, View, Controller (MVC) Example, sees us work through the MVC pattern by building a toy MVC system. You are definitely encouraged to download the code for this chapter.

Chapter 9, Dependency Injection Example, as in Chapter 8, Model, View, Controller (MVC) Example, looks to learn by doing, and this time our goal is to understand all about DI. We will create an entire toy DI container to understand how this pattern works.

Chapter 10, Composer for Dependencies, introduces Composer—one of the most important things to happen in the PHP world. We will learn how to use Composer to use third-party packages in our projects.

Chapter 11, Creating Your Own Composer Package, continues with Composer but this time looks at how we can use it to create our own packages, share them with our private projects, and even publish them for the benefit of the PHP community.

Chapter 12, The Awesomeness That Is 8.1, the final chapter of the book, is all about PHP 8.1 and the excellent new features that are included in this new release. It is not an exhaustive list but instead focuses on a selection of features that are most likely to matter to you day to day.

To get the most out of this book

This is a book for PHP developers, and the main thing that you need is a way to write and run PHP code. For editing, modern development practices have very much embraced the IDE as an essential tool. Popular IDEs include PhpStorm and NetBeans. You may choose to use a more lightweight code editor, such as VSCode or Sublime Text, if you prefer.

You will need to be able to run PHP 8 code on the command line, and if you want to run the last chapter, then you will need PHP 8.1 as well. Installing PHP is beyond the scope of this book and is dependent on your specific operating system or virtualization technology.

Practically all code samples in this book (excluding very minor snippets) are included in the public Git repository available on GitHub at https://github.com/PacktPublishing/The-Art-of-Modern-PHP-8. You are strongly encouraged to clone or download all this code so that you can load it in your IDE, run it, and generally play around with it.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can clone or download the example code files for this book from GitHub at https://github.com/PacktPublishing/The-Art-of-Modern-PHP-8. If there's an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The preceding code has shown us the fact that an instance of ChildClass passes as an instance of all of its parent items all the way up the inheritance tree."

A block of code is set as follows:

{

"php": ">=7.0.0",

"egulias/email-validator": "^2.0|^3.1",

"symfony/polyfill-iconv": "^1.0",

"symfony/polyfill-mbstring": "^1.0",

"symfony/polyfill-intl-idn": "^1.10"

}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<?php

declare(strict_types=1);

namespaceBook\Part3\Chapter8\ToyMVC\View\Data;

interfaceTemplateDataInterface

{

}

Any command-line input or output is written as follows:

cd /my/project/root/directory

composer init

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: "It's very easy to remove a package from Packagist. Simply click the red Delete button."

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read The Art of Modern PHP 8, we’d love to hear your thoughts! Please click here to go straight to the Amazon review pagefor this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Section 1 – PHP 8 OOP

Object-Oriented Programming (OOP) is a fundamental feature of modern PHP. In this first section, we are going to go over this in detail, starting with the basics and working our way up to more advanced features.

This section contains the following chapters:

Chapter 1, Object-Oriented PHP Chapter 2, Inheritance and Composition, Encapsulation and Visibility, Interfaces and ConcretionsChapter 3, Advanced OOP Features