Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Building RESTful Web Services with PHP 7
Building RESTful Web Services with PHP 7

Building RESTful Web Services with PHP 7: Lumen, Composer, API testing, Microservices, and more

eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Building RESTful Web Services with PHP 7

PHP7, To Code It Better

PHP7 came with many new features and changes. However, none of them were specifically for REST or web services. In fact, REST does not have any direct relation with language constructs. This is because REST is an architecture, while a language is there to provide constructs for implementation. So, does that mean PHP7 has some construct or feature which can make this implementation better? Yes and no. It depends on what we mean by implementation.

If we mean just getting a request and returning a response then No, there is no such specific feature. But, any RESTful Web Service is related to an entity, and an entity can have its own logic. So to provide RESTful Web Service for that entity, we need to write that logic as well. For this purpose, we will need to write more PHP code than just getting a request and returning a response. So to keep the code simple...

Scalar type declaration

In PHP7, we can now declare the type of parameters being passed to a function. They could be only user defined classes in previous versions, but now they can be scalar types as well. By scalar type, we mean basic primitive types, such as int, string, and float.

Previously, to validate an argument passed to a function, we needed to use some sort of if-else. So, we used to do something like this:

<?php
function add($num1, $num2){
if (!is_int($num1)){
throw new Exception("$num1 is not an integer");
}
if (!is_int($num2)){
throw new Exception("$num2 is not an integer");
}

return ($num1+$num2);
}

echo add(2,4); // 6
echo add(1.5,4); //Fatal error: Uncaught Exception: 1.5 is not an integer

Here we used if to make sure that the type of the variables $num1 and $num2 is int, otherwise we are throwing an exception...

Return type declaration

Just like parameter type, there is also a return type; it is also optional but it is a safe practice to specify the return type.

This is how we can declare a return type:

<?php
function add($num1, $num2):int{
return ($num1+$num2);
}

echo add(2,4); //6
echo add(2.5,4); //6

As you can see in the case of 2.5 and 4, it should be 6.5, but as we have specified int as a return type, it is performing implicit type conversion. To avoid this and to obtain an error instead of an implicit conversion, we can simply enable a strict type, as follows:

<?php
declare(strict_types=1);
function add($num1, $num2):int{
return ($num1+$num2);
}

echo add(2,4); //6
echo add(2.5,4); //Fatal error: Uncaught TypeError: Return value of add() must be of the type integer, float returned

Null coalescing operator

The Null coalescing operator (??) is a syntactical sugar, but a very important one. Previously in PHP5 when we were having some variable which could be undefined, we used the ternary operator as follows:

$username = isset($_GET['username']) ? $_GET['username'] : '';

However, now in PHP7, we can simply write:

$username = $_GET['username'] ?? '';

Although this is just a syntactical sugar, it can save time and make code cleaner.

Spaceship operator

Scalar type declaration


In PHP7, we can now declare the type of parameters passed to a function. They could be only user defined classes in previous versions, but now they can be scalar types as well. By scalar type, we mean basic primitive types, such as int, string, and float.

Previously, to validate an argument passed to a function, we needed to use some sort of if-else. So, we used to do something like this:

<?php
function add($num1, $num2){
    if (!is_int($num1)){
        throw new Exception("$num1 is not an integer");
    }
    if (!is_int($num2)){
        throw new Exception("$num2 is not an integer");
    }

    return ($num1+$num2);
}

echo add(2,4);  // 6
echo add(1.5,4); //Fatal error:  Uncaught Exception: 1.5 is not an integer

Here we used if to make sure that the type of the variables $num1 and $num2 is int, otherwise we are throwing an exception. If you are a PHP developer from the earlier days who likes to write as little code as possible, then chances are that you were...

Return type declaration


Just like parameter type, there is also a return type; it is also optional it is a safe practice to specify the return type.

This is how we can declare a return type:

<?php
function add($num1, $num2):int{
    return ($num1+$num2);
}

echo add(2,4); //6
echo add(2.5,4); //6

As you can see in the case of 2.5 and 4, it should be 6.5, but as we have specified int as a return type, it is performing implicit type conversion. To avoid this and to obtain an error instead of an implicit conversion, we can simply enable a strict type, as follows:

<?php
declare(strict_types=1);
function add($num1, $num2):int{
    return ($num1+$num2);
}

echo add(2,4); //6
echo add(2.5,4); //Fatal error:  Uncaught TypeError: Return value of add() must be of the type integer, float returned

Null coalescing operator


The Null coalescing operator (??) is a syntactical sugar, but a important one. Previously in PHP5 when we were having some variable which could be undefined, we used the ternary operator as follows:

$username = isset($_GET['username']) ? $_GET['username'] : '';

However, now in PHP7, we can simply write:

$username = $_GET['username'] ?? '';

Although this is just a syntactical sugar, it can save time and make code cleaner.

Spaceship operator


The spaceship operator is also a shortcut comparison and is useful in user defined sorting functions. I am not going into detail about this, as it is already explained enough in its documentation: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.spaceship-op.

Group use declarations


Classes, functions, and constants, which are in the same namespace, can now imported in a single use statement. Previously, multiple use statements were required for that. Here is an example to understand it better:

<?php
// use statement in Pre-PHP7 code
use abc\namespace\ClassA;
use abc\namespace\ClassB;
use abc\namespace\ClassC as C;

use function abc\namespace\funcA;
use function abc\namespace\funcB;
use function abc\namespace\funcC;

use const abc\namespace\ConstA;
use const abc\namespace\ConstB;
use const abc\namespace\ConstC;

// PHP 7+ code
use abc\namespace\{ClassA, ClassB, ClassC as C};
use function abc\namespace\{funcA, funcB, funcC};
use const abc\namespace\{ConstA, ConstB, ConstC};

As you can see from this example, how convenient the group use statement is, it is clearly visible. Curly braces with comma separated values are used to group values such as {classA, classB, classC as C}, resulting in the grouped use statement, instead of separately using...

Generator-related features


Although came in PHP5.5, most PHP developers don't use them and most probably do not know about generators. So, let's first discuss generators.

What are generators?

As stated in the PHP manual:

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the iterator interface.

OK, here is a more detailed and easy-to-understand definition from the same source, php.net:

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

For example, you can simply write a function returning a of different...

Anonymous classes


Just like anonymous functions, now there anonymous classes in PHP. Note that if an object is required, then most probably we need some specific type of object and not just a random one, for example:

<?php
class App
{
    public function __construct()
    {
        //some code here
    }
}

function useApp(App $app)
{
    //use app somewhere
}

$app = new App();
useApp($app);

Note that a specific type of object was required in the useApp() function, and this type App couldn't be defined if it wasn't a class. So, where and why would we use an anonymous class with some specific functionality in it? We may need it in case we need to pass a class implementing some specific interface or extending some parent class, but only want to have this class used in one place. In that case, we can use an anonymous class. Here is the same example given in the PHP7 documentation so that it will be easy for you to follow up:

<?php
interface Logger {
    public function log(string $msg...

Closure::call()


Binding an object scope with a closure is an efficient way to use a closure with different objects. At the same time, it is also a simple way to use different closures having different behaviors an object in different places. This is because it binds the object scope with a closure at runtime without inheritance, composition, and so on. However, previously we didn't have the Closure::call() method; we had something like this:

<?php
// Pre PHP 7 code
class Point{
    private $x = 1; 
    private $y = 2;
}

$getXFn = function() {return $this->x;};
$getX = $getXFn->bindTo(new Point, 'Point');//intermediate closure
echo $getX(); // will output 1

But now with Closure::call(), the same code can be written as follows:

<?php
//  PHP 7+ code
class Point{
    private $x = 1; 
    private $y = 2;
}

// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new Point); // outputs 1 as doing same thing

Both code snippets perform the same action. However, PHP7...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Leverage the Lumen framework to build RESTful API endpoints for your applications
  • • Understand how to increase efficiency and security of your web service.
  • • Learn to apply the concepts by implementing the examples covered in the book

Description

REST is the most wide spread and effective standard to develop APIs for internet services. With the way PHP and its eco-system has modernized the way code is written by simplifying various operations, it is useful to develop RESTful APIs with PHP 7 and modern tools. This book explains in detail how to create your own RESTful API in PHP 7 that can be consumed by other users in your organization. Starting with a brief introduction to the fundamentals of REST architecture and the new features in PHP 7, you will learn to implement basic RESTful API endpoints using vanilla PHP. The book explains how to identify flaws in security and design and teach you how to tackle them. You will learn about composer, Lumen framework and how to make your RESTful API cleaner, secure and efficient. The book emphasizes on automated tests, teaches about different testing types and give a brief introduction to microservices which is the natural way forward. After reading this book, you will have a clear understanding of the REST architecture and you can build a web service from scratch.

Who is this book for?

This book is for PHP developers who wish to learn about the REST architecture to be able to build and consume REST APIs in their applications.

What you will learn

  • • Understand the REST API architecture and its benefits
  • • Write RESTful API web services in PHP 7
  • • Address security-elated issues in a REST API
  • • Leverage the importance of automated testing and write tests for API endpoints
  • • Identify security flaws in our current API endpoints and tackle them effectively
  • • Observe the working of Lumen microframeworks and write RESTful web services in it

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 11, 2017
Length: 244 pages
Edition : 1st
Language : English
ISBN-13 : 9781787283640
Vendor :
Oracle
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Sep 11, 2017
Length: 244 pages
Edition : 1st
Language : English
ISBN-13 : 9781787283640
Vendor :
Oracle
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 110.97
PHP 7 Data Structures and Algorithms
€36.99
Mastering PHP 7
€36.99
Building RESTful Web Services with PHP 7
€36.99
Total 110.97 Stars icon
Banner background image

Table of Contents

9 Chapters
RESTful Web Services, Introduction and Motivation Chevron down icon Chevron up icon
PHP7, To Code It Better Chevron down icon Chevron up icon
Creating RESTful Endpoints Chevron down icon Chevron up icon
Reviewing Design Flaws and Security Threats Chevron down icon Chevron up icon
Load and Resolve with Composer, an Evolutionary Chevron down icon Chevron up icon
Illuminating RESTful Web Services with Lumen Chevron down icon Chevron up icon
Improving RESTful Web Services Chevron down icon Chevron up icon
API Testing – Guards on the Gates Chevron down icon Chevron up icon
Microservices Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.4
(5 Ratings)
5 star 20%
4 star 0%
3 star 20%
2 star 20%
1 star 40%
Usman Faisal Dec 10, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A great coverage to all topics needed to build REStful Web Services with PHP7. Prior knowledge of PHP required to deep dive into this book. Though this book mainly revolve around Lumen/Laravel Framework but in general one can get the core concept and implementation of robust, elegant and secure Restful API development. The book also contain code samples and in addition some new features which introduced in PHP7.
Amazon Verified review Amazon
Manu Feb 22, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
It's a good book in terms of gathering interesting information related to Lumen, but doesn't worth that price. Too expensive for what you get.
Amazon Verified review Amazon
MarkSR Dec 13, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Could use English editing, but more than that it's just sparse --- many pages are just a title followed by a couple of sentences. It goes into way too much detail on fairly basic REST concepts, but quotes PHP documentation with very little comment on more complex topics. Worse, the most complex concepts like closure are dealt with in a few sentences that read like a parody of bad, circular tech writing. Sample code is provided by chapter number, but chapters aren't numbered in the TOC. Seems like it was knocked together really quickly by people with no knowledge of publishing.
Amazon Verified review Amazon
Tim Vervoort Apr 27, 2020
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Not a lot of information about Lumen, testing or Microservices. Quite a lot of typos. Mostly, the text just refers to online blog posts or documentation. The amount of new/practical information could be published in a 10-minute read blog post. I paid €45,56 which is more than double than what its worth. Not recommended.
Amazon Verified review Amazon
Marco May 03, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Update 3:Sono arrivato al capitolo su Lumen e le routes... ebbene, con l'attuale versione di Lumen, il codice fornito non funziona.Già Lumen non mi è chiarissimo... senza poi un minimo di spiegazione, mi sa che ho buttato il mio tempo.Da non comprare.--------Update 2:Ho riscontrato un errore di digitazione nel codice (lo segnalerò sul sito dell’editore) quando viene fatto l’inserimEnto degli utenti. Trovo altresì limitato indicare il plugin Postman solo per Chrome, quando esiste l’app standalone multipiattaforma.Adeguando alcune parti di codice sono riuscito a fare l’inserimento dei dati via endpoint. Dopodiché più niente... magari è qualcosa legato al server oppure al codice editato. Appena possibile ci lavorerò sopra per vedere di capire cosa non funziona.——————Update:Dopo diverse ore di ricerca online, ho capito che il problema di fondo è che i webserver classici, come Apache o NGINX, non funzionano come il server integrato di PHP, ossia non bypassano nativamente il file index.php.Per far funzionare il webservice di esempio dovrei quindi indicare /api/index.php/posts e non /api/posts.Tuttavia con un'adeguata configurazione di Apache e un file .htaccess è possibile risolvere il problema.Per ora 4 stelle (sulla fiducia), ma se dovessi avere altri problemi riaggiornerò questa recensione.-------I primi capitoli, che sono pressochè teorici, sono scritti in un inglese a tratti approssimativo. Ho dovuto attingere a fonti online per capire meglio certi concetti. Anche perchè in un paio di punti l'autore rimanda a siti esterni.I problemi sono iniziati dal terzo capitolo: dopo aver impostato tutta la struttura del webservice, utilizzando Apache, non c'è modo di far funzionare il progetto.Sono 2 ore che tento di farlo funzionare su un server reale (con apache) ma proprio niente. Purtroppo il libro non spiega come configurare il server web, riferendosi sempre al comando manuale di PHP.In effetti utilizzandolo il webserver integrato di PHP lo script funziona, ma non mi è chiaro come impostare il tutto su di un servizio di hosting pubblico (dove non posso lanciare il comando da php). Un po' perplesso... andrò avanti e nel caso aggiornerò la mia valutazione.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.