com https://fb.com/tailieudientucntt PHP 7 Programming Blueprints Learn how to exploit the impressive power of PHP 7 with this collection of practical project blueprints – begin building better applications for the web today! Jose Palala Martin Helmich BIRMINGHAM - MUMBAI CuuDuongThanCong.com https://fb.com/tailieudientucntt PHP 7 Programming Blueprints Copyright © 2016 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 authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be 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. First published: October 2016 Production reference: 2061016 Published by Packt Publishing Ltd.
Livery Place 35 Livery Street Birmingham B3 2PB, UK.com https://fb.com/tailieudientucntt Credits Authors Copy Editor Jose Palala Safis Editing Martin Helmich Reviewer Project Coordinator Shuvankar Sarkar Ulhas Kambali Commissioning Editor Proofreader Kunal Parikh Safis Editing Acquisition Editor Indexer Chaitanya Nair Rekha Nair Content Development Editor Production Coordinator Onkar Wani Melwyn Dsa Technical Editor Cover Work Murtaza Tinwala Melwyn Dsa CuuDuongThanCong.com https://fb.com/tailieudientucntt About the Authors Jose Palala has been working professionally with PHP for at least 8 years. He has experience working with PHP frameworks such as Eden PHP, CodeIgniter, Laravel and Zend. He has worked for Philippine-based IT companies for at least 8 years, working on projects ranging from internal corporate systems and CMS websites. In his spare time, he regularly contributes back to the tech community in the Philippines.
I would like to thank everyone at Packt Publishing, it’s been great working with them since Day 1. Super thanks to all to my colleagues, friends and family who have helped me to become a better developer and have helped me become what I am today. Martin Helmich holds a Master's degree in Computer Science from the University of Applied Sciences in Osnabrück. He works as a software architect and specializes in building distributed applications using web technologies and Microservice Architectures.
Besides programming in Go, PHP, Python and Node.JS, he also builds infrastructures using configuration management tools like SaltStack and container technologies like Docker. He is an open source enthusiast and likes to make fun of people who are not using Linux. In his free time, you'll probably find him coding on one of his open source pet projects, listening to music or reading science-fiction literature.com https://fb.com/tailieudientucntt About the Reviewer Shuvankar Sarkar is an IT analyst and experienced in C#, .NET, PHP and web development. He is a technology enthusiast and maintains his blog at http://shuvankar.
You can follow him on Twitter at @sonu041. He is interested in computer security as well. I would like to thank my family for making my life easier and full of happiness.com https://fb.com/tailieudientucntt www.com eBooks, discount offers, and more Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at customercare@packtpub.com for more details.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library.
Here, you can search, access, and read Packt's entire library of books. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser CuuDuongThanCong.com https://fb.com/tailieudientucntt Table of Contents Preface 1 Chapter 1: Create a User Profile System and use the Null Coalesce Operator 6 The null coalesce operator 7 Separation of Concerns 8 Creating views 8 Create a profile input form 10 Admin system 13 Summary 17 Chapter 2: Build a Database Class and Simple Shopping Cart 18 Building the database abstraction class 19 Raw query method 19 Create method 19 Read method 20 Select all method 20 Delete method 21 Update method 21 first_of method 22 last_of method 22 iterate_over method 22 searchString method 22 Using the convert_to_json method to implement a simple API 23 Shopping Cart 23 Building the shopping items list 24 Item template rendering function 24 Adding checkboxes to the Shopping List page 27 Cookies in PHP 28 Building the Checkout page 29 Thank you page 32 Installing TCPDF 33 Admin for managing purchases 38 Summary 40 Chapter 3: Building a Social Newsletter Service 41 CuuDuongThanCong.com https://fb.com/tailieudientucntt Authentication system 41 Creating a social login for members 47 Member dashboard 52 Marketers dashboard 56 Administration system for managing marketers 57 Custom template for our newsletter 60 Link tracking 63 AJAX socket chat for support 66 Introduction to socket.io 66 Summary 73 Chapter 4: Build a Simple Blog with Search Capability using Elasticsearch 75 Creating the CRUD and admin system 75 Seeding the post table 80 What is Elasticsearch? 80 Installing Elasticsearch and the PHP client 81 Building a PHP Elasticsearch tool 85 Adding documents to our Elasticsearch 87 Querying Elasticsearch 88 Installing Logstash 88 Setting up the Logstash configuration 89 Installing PHP Redis 89 Encoding and decoding JSON messages 91 Storing Apache logs in Elasticsearch 92 Getting filtered data to display with Highcharts 93 Dashboard app for viewing Elasticsearch logs 99 Simple search engine with result caching 101 Cache basics 103 Cache invalidation of Redis data 103 Using browser localStorage as cache 104 Working with streams 106 Storing and searching XML documents using PHP 108 Using Elasticsearch to search a social network database 108 Displaying randomized search engine results 110 Summary 112 Chapter 5: Creating a RESTful Web Service 113 RESTful basics 114 REST architectures 114 Common HTTP methods and response codes 115 First steps with the Slim framework 116 [ ii ] CuuDuongThanCong.com https://fb.com/tailieudientucntt Installing Slim 116 A small sample application 117 Accepting URL parameters 118 Accepting HTTP requests with a message body 119 The PSR-7 standard 120 Middleware 122 Implementing the REST service 124 Designing the service 124 Bootstrapping the project 125 Building the persistence layer with MongoDB 127 Adding and retrieving users 132 Listing and searching users 137 Deleting profiles 140 Validating input 143 Streams and large files 145 Profile image upload 145 Using GridFS storage 149 Summary 152 Chapter 6: Building a Chat Application 153 The WebSocket protocol 153 First steps with Ratchet 154 Architectural considerations 154 Getting started 155 Testing WebSocket applications 158 Playing with the event loop 159 Implementing the chat application 162 Bootstrapping the project server-side 162 Bootstrapping the HTML user interface 164 Building a simple chat application 165 Receiving messages 170 Sending messages 171 Testing the application 171 Keeping the connection from timing out 172 Deployment options 173 Bridging Ratchet and PSR-7 applications 176 Accessing your application via the web server 182 Adding authentication 183 Creating the login form 184 Checking the authorization 188 [ iii ] CuuDuongThanCong.com https://fb.com/tailieudientucntt Connecting users and messages 190 Summary 192 Chapter 7: Building an Asynchronous Microservice Architecture 193 The target architecture 193 ZeroMQ patterns 195 Request/reply pattern 195 Publish/subscribe pattern 196 Push/pull pattern 196 Bootstrapping the project 197 Building the inventory service 198 Getting started with ZeroMQ REQ/REP sockets 198 Using JsonRPC for communication 200 Making the inventory service multithreaded 205 Building the checkout service 209 Using react/zmq 209 Working with promises 211 Building the mailing service 219 Building the shipping service 223 PUSH/PULL for beginners 223 Fan-out/fan-in 228 Bridging ZeroMQ and HTTP 230 Summary 236 Chapter 8: Building a Parser and Interpreter for a Custom Language 237 How interpreters and compilers work 238 Languages and grammars 239 Your first PEG parser 242 Evaluating expressions 246 Building an Abstract Syntax Tree 249 Building a better interface 254 Evaluating variables 256 Adding logical expressions 259 Comparisons 260 The “and” and “or” operators 263 Conditions 265 Working with structured data 268 Working with objects 271 Optimizing the interpreter by adding a compiler 273 Verifying performance improvements 281 [ iv ] CuuDuongThanCong.com https://fb.com/tailieudientucntt Summary 285 Chapter 9: Reactive Extensions in PHP 286 An introduction to observables 286 Introduction to event loop and ReactiveX 287 delay 289 defer 289 Scheduler 290 recursive-scheduler 290 map and flatMap 292 reduce 292 toArray 293 merge 294 do 294 scan 295 zip 296 Parsing logs through a Reactive scheduler 297 Event queues with ReactiveX 298 Summary 299 Index 300 [v] CuuDuongThanCong.com https://fb.com/tailieudientucntt Preface PHP is a great language for developing web applications. It is essentially a server-side scripting language that is also used for general-purpose programming. PHP 7 is the latest version, which provides major backward-compatibility breaks and focuses on providing improved performance and speed.
With the rise in demand for high performance, this newest version contains everything you need to build efficient applications. PHP 7 provides improved engine execution, better memory usage, and a better set of tools allowing you to maintain high traffic on your websites with low-cost hardware and servers through a multithreading web server. What this book covers Chapter 1, Create a User Profile System and use the Null Coalesce Operator, we'll discover new PHP 7 features and build app for storing user profiles. Chapter 2, Build a Database Class and Simple Shopping Cart, we'll create a simple database layer library which will help us access our database.
We'll cover some tips on making our queries secure, and how to make our coding simpler and more succinct with PHP 7. Chapter 3, Building a Social Newsletter Service, we'll be building a social newsletter service, which will have a way for users to sign in using their social login and allow them to register to a newsletter. We'll also make a simple admin system for managing the newsletters. Chapter 4, Build a Simple Blog with Search Capability using Elasticsearch, you will learn how to create a blog system, experiment with ElasticSearch and how to apply it in your code.
Also, you will learn how to create a simple blog application and store data into MySQL. Chapter 5, Creating a RESTful Web Service, shows you how create a RESTful web service that can be used to manage user profiles. The service will be implemented using the Slim micro framework and use a MongoDB database for persistence. The chapter also covers the basics of RESTful web services, most importantly the common HTTP request and response methods, the PSR-7 standard and PHP 7’s new mongodb extension.com https://fb.com/tailieudientucntt Preface Chapter 6, Building a Chat Application, describes the implementation of a real-time chat application using WebSockets.
You will learn how to use the Ratchet framework to build stand-alone WebSocket and HTTP servers with PHP and how to connect to WebSocket servers in a JavaScript client application. We will also discuss how you can implement authentication for WebSocket applications and how to deploy them in a production environment. Chapter 7, Building an Asynchronous Microservice Architecture, covers the implementation of a (small) microservice architecture. Instead of RESTful web services, you will use ZeroMQ in this chapter for network communication, an alternative communication protocol that focuses on asynchronicity, loose coupling and high performance.
Chapter 8, Building a Parser and Interpreter for a Custom Language, describes how to use the PHP-PEG library to define a grammar and implement a parser for a custom expression language that can be used to add end-user development features to enterprise applications. Chapter 9, Reactive Extensions in PHP, here we'll look into the Reactive extensions library for PHP, and and try to build a simple scheduled app.