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

Arrow left icon
Profile Icon Waheed ud din
Arrow right icon
$19.99 per month
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.4 (5 Ratings)
Paperback Sep 2017 244 pages 1st Edition
eBook
$35.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Waheed ud din
Arrow right icon
$19.99 per month
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.4 (5 Ratings)
Paperback Sep 2017 244 pages 1st Edition
eBook
$35.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$35.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781787127746
Vendor :
Oracle
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 146.97
PHP 7 Data Structures and Algorithms
$48.99
Mastering PHP 7
$48.99
Building RESTful Web Services with PHP 7
$48.99
Total $ 146.97 Stars icon

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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.

Modal Close icon
Modal Close icon