Building RESTful Web Services in PHP7


Here is the book I have written recently on RESTful web services in PHP 7. The title is Building RESTful Web Services in PHP7 and is available on Amazon. You are probably wondering that why another PHP book. Why about RESTful web services. Many people consider RESTful web services as hitting a URI and getting JSON in response. However, this is a misconception. RESTful web service is more than that. And when it comes to Building RESTful web services then there  are numerous important things to consider.

Although there are already books on PHP and RESTful web services, this book is important because PHP and its ecosystem has evolved. “PHP7” in the title is to tell that we are talking about modern tools and ecosystem of PHP. Let me provide you detail of book in structured way. Let’s discuss different aspects of the book one by one.

Who is this book Useful for?

  • Anyone who have some basic PHP knowledge and want to build RESTful Web Service.
  • Developers who know basic PHP and have developed some basic dynamic website.
  • Developers who know basic PHP and have developed some basic dynamic website.
  • Developers who have learned PHP and worked mostly in Open source CMS like WordPress etc.
  • Developers who have used modern frameworks but not sure about critical pieces required to build RESTful API.
  • A seasoned PHP Developer, have created very basic API that returns data but want to make himself familiar with how it should be done according to REST standards and how it will work when authentication etc comes in and how to write tests for it.

What will Reader Learn?

  • REST API architecture and its benefits
  • How to write RESTful API web services in PHP7
  • To address security related issues in a REST API
  • Importance of automated testing and to write tests for API endpoints
  • Will be introduced to Micro-services architecture
  • Will understand security flaws in our API endpoints and tackle them effectively
  • The working of Lumen micro-framework and writing RESTful web services in it

Content of Book, Chapter by Chapter:

Chapter 1 RESTful web services, Introduction and Motivation:

This chapter is about introduction to Web Services, REST Architecture, RESTful Web Services, its comparison to other Web Services. HTTP Verbs, RESTful endpoints. It also explains RESTful web services concept by the use of Blog example and then talk about Response format and Response Code.

Chapter 2, PHP7, To Code It Better :

This chapter includes new features or changes on PHP7, which we will either use in this book or which are very important and worth discussing. As new features include features related to generators as well so introduced generators to user. Although generators were there already but rarely people use it. So this chapter also tells us about generators with examples.

Chapter 3, Creating RESTful Endpoints :

This chapter is about creating REST API endpoints for CRUD operations of a blog post in Vanilla PHP. Will also tell manual way of testing API endpoints through a REST client named as Postman.

Chapter 4, Reviewing Design Flaws and Security Threats :

In this chapter we will review what we have built in Chapter 3 and will highlight problems and flaws in it so that we can later improve that. It will include some security flaws as well. Some of the flaws and security threats in our application also fixed in this chapter while told about some of threats solution but not solved in this chapter but pointed towards open source package.

Chapter 5, Load and Resolve with Composer, an Evolutionary:

This chapter is about an evolutionary tool in PHP eco-system that is composer.This is not just an autoloader or package installer but a dependency manager. So one knows more about composer in this chapter.

Chapter 6, Illuminating RESTful Web Services with Lumen:

In this chapter we will introduce a micro-framework named Lumen. And will rewrite our RESTful web services endpoints in this micro-framework and will review how this tool will significantly improve our development speed as well as application structure.

In this chapter, users can first understand the Lumen framework, its components and then its usage to create RESTful web services’ endpoints.

Chapter 7, Improving RESTful web services:

This chapter will improve what is done in chapter 6 and we will learn and improve lot of stuff. User will create authentication, will make Transformer to separate how JSON structure should look like. Also user will improve web service in terms of security and will also learn about SSL.

Chapter 8, API Testing – Guards on the Gate:

This chapter introduces the need of Automated Tests. Will introduce different type of tests and then focus on API testing and teach user an automated testing framework named CodeCeption and will then write API tests in that testing framework.

Chapter 9, Microservices – An introduction

This chapter is about micro-services architecture. So we will understand and see benefits and challenges of Micro-services and will look into some of possible solutions or trade-offs. Introducing a new topic at the end of book normally doesn’t make sense. However, here this chapter point user towards Micro-services architecture that seems like the logical next step about how RESTful web services should be organized.

 

This is how I could present the content of the book. Feel free to let me know of your opinion. If you liked the book and want to buy then you can buy it from amazon:

Fix Uncaught ReflectionException: Class log does not exist …/laravel/framework/…

I again got this error which left me no clue of what happened wrong and how can I fix it.

PHP Fatal error: Uncaught ReflectionException: Class log does not exist in .../vendo/laravel/framework/src/Illuminate/Container/Container.php:741

I tried to find solution on google for a while and came to know that this don’t tell what acually went wrong. There can be different things which can be in different case. And you will find nothing other than someone will be telling that this error just mean something crashed earlier on before that interface was bound. So it tells nothing useful.

I found different reasons for this, but most commonly it was after you updated something in your system, which effected some extension of php or something else went wrong.

Here I am not going to dig deeper into why it happened because there can be lot of different reasons, I am just trying to tell a way by which I came to know the reason and fixed it. It happened to me twice in last few months and I found nothing on stackoverflow so that’s why I am writing it here.

So here are steps to find the reason and fix:

  1. Good thing about Laravel is that it checks some obvious dependencies which are required for Laravel to function properly. So go to some other directory and try installing Laravel’s same version there.  You can install it using
    composer create-project --prefer-dist laravel/laravel blog

    while in my case I was using Laravel bootstrap so I ran

    composer create-project graham-campbell/bootstrap-cms --prefer-dist -s dev
  2. It will show you missing dependencis, so you can see the dependencies and try to resolve them by installing missing extensions. In my case it was ext-mbstring  missing and in someone else’s case it was php-mysql extension missing. So install whatever extension is missing in your case.
  3. After installing extension don’t forget to restart apache:
    sudo service apache2 restart
  4. Once you have those extensions installed and your able to complete Laravel installation, go back to actual Laravel installation directory where you were actually facing above mentioned issue.
  5. Once you are there, give all permissions to `storage` and `bootstrap/cache` directories in Laravel installation by doing:
    sudo chmod 777 storage -R
    sudo chmod 777 bootstrap/cache -R
  6.  Now execute following command:
    php artisan clear-compiled
  7. If you see error like:
    PHP Fatal error: Trait 'Illuminate\Auth\Access\HandlesAuthorization' not found in ...dynamic/bootstrap/cache/compiled.php on line 737
    Script php artisan clear-compiled handling the post-install-cmd event returned with an error[RuntimeException]Error Output: PHP Fatal error: Trait 'Illuminate\Auth\Access\HandlesAuthorization' not found in /var/www/html.../bootstrap/cache/comp

    Delete the contents of the bootstrap/cache folder, then run

    php artisan app:update 

    and try running

     php artisan clear-compiled

    again.

  8. After doing so just run:
    composer dump-autoload
  9. And then go to your browser and try to reload. Most probably it should be working as this is how I had it working twice.

In case it still don’t work, then post it in comment and we can try to dig into that.

Configuring and using Laravel with MongoDB

This entry is part 1 of 1 in the series MongoDB

In this article we will see how to use MongoDB with Laravel (PHP framework). So first we need to install MongoDB and Laravel.

Laravel and MongoDB installation:

We will install Laravel and MongoDB one by one and I assume that you have PHP already installed with a web server.

Laravel Installation:

I assume LAMP environment is already configured. You can install Laravel simply through composer using following command if you have Composer already installed.

composer create-project laravel/laravel --prefer-dist

If you don’t know about composer or want to know more detailed installation and configuration of Larvel then Laravel documentation explained it in detail: http://laravel.com/docs/5.1#installation

MongoDB installation:

If you haven’t already installed MongoDB then MongoDB have separate guides for installing it own different Operating Systems. So check that: http://docs.mongodb.org/manual/installation/

Current version of MongoDB at this time is 3.x. But it you have MongoDB version 2.x installed and running on your machine then still feel free to use this tutorial, as it will work for 2.x as well and it have stuff related to 2.x difference in user creation section.

MongoDB driver for PHP:

PHP have official MongoDB driver that is called Mongo. It contains MongoClient class that is used by several packages which connect PHP with MongoDB.

You can install MongoDB driver on Windows OS using steps mentioned here: http://haafiz.me/development/installing-mongodb-driver-mongoclient-for-php-on-windows

To install MongoDB driver on ubuntu  or other Linux distributions, follow steps mentioned here: http://haafiz.me/development/installing-mongodb-driver-mongoclient-for-php-on-ubuntu

To check if MongoDB driver is successfully installed, try instantiating MongoClient class.

Laravel Package for MongoDB:

Laravel have several MongoDB related packages and some of them not work for Laravel 5.x (current versions at time of this writing). Based on several factors like number of contributers, number of commits, releases and documentation on github, simplicity and ease of use, I suggest using jenssegers/laravel-mongodb which is also knowns as Moloquent.

Installation:

To install for Laravel 5.1, install latest stable version using composer.

composer require jenssegers/mongodb

In config/app.php :

Add below line in providers array:

Jenssegers\Mongodb\MongodbServiceProvider::class,

And add in same file, add below line in aliases array:

'Moloquent' => 'Jenssegers\Mongodb\Model',

Moloquent Configurations:

In app/config/database.php, add MongoDB connection detail:

'mongodb' => array(
            'driver' => 'mongodb',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', 27017),
            'database' => env('DB_DATABASE', 'l5'),
            'username' => env('DB_USERNAME', 'l5'),
            'password' => env('DB_PASSWORD', '123456'),
            'options' => array(
                'db' => 'admin' // sets the authentication database required by mongo 3
            )
        ),

and make this mongodb connection, default connection.

'default' => env('DB_CONNECTION', 'mongodb'),

If you have installed MongoDB just now then you will not have Database, username and password to provide in connection info. For that purpose you need to first create database, username and password.

Setting up MongoDB Database and User:

To create a MongoDB database, you need to start, execute “mongo” from command line. To do so you need to add MongoDB bin directory to your system path. And then run:

mongod

This will run mongo server to listen calls.

In case you see error like: “data/db not found” , then that means that this path doesn’t exist on your system or don’t have appropriate permissions. So either create and assign appropriate permissions at that location or with appropriate permissions create DB data folder at some other custom location and give DB path like:

mongod --dbpath custom/directory/path

Once it is running, mongo server will be listening for client calls. So you need to run mongo shell client by simply opening another shell instance and run :

mongo

This will open mongoDB shell.

Creating Database in MongoDB:

Using mongo client shell, you need to create your database

> use dbname
> db.insert({"key":"value"})

By executing above statement, use statement switches DB to “dbname”, and assigns value “dbname” to variable “db”  so you can use your desired DB name. If “dbname” is name of existing database then it will switch to that database or else it will create that Database if atleast one record is added to that database.

Setting up First User and access:

If you are using Mongo 3.0 or above, first of all you need to switch to “admin” database and creating a user with administrative rights for all databases.

> use admin
> db.createUser(
  {
    user: "siteUserAdmin",
    pwd: "password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

You can replace “siteUserAdmin” and “password” from above code with your desired admin username and password. Role “userAdminAnyDatabase” is a special role for administrating all databases and this role is at “admin” database.

Once you have this Admin user on admin DB, you need to create user for your required DB, in our case “dbname”.

> use records
> db.createUser(
  {
    user: "recordsUserAdmin",
    pwd: "password",
    roles: [ { role: "userAdmin", db: "records" } ]
  }
)

Here you can replace “recordsUserAdmin”,”password” and “dbname” with desired username, password and your intended database name. And this will set your admin user for that database.

If you are using MongoDB version 2.x then user creation is different. In version 2.x db.createUser() function is not present. You need to use db.addUser() like:

> use products
> db.addUser( { user: "user1",
              pwd: "password",
              roles: [ "readWrite", "dbAdmin" ]
            } )

So now you have DBname, username and password to put in you Laravel app/config/database.php

Extending Models from Moloquent:

Only thing that is left is to extend your models from “Moloquent” instead of “Eloquent”.  So a typical model will look like this:

<?php
namespace App\Models;

use Moloquent;

/**
 * Category Model
 *
 * @author Hafiz Waheeduddin
 */
class Category extends Moloquent
{
 public function tasks()
 {
 return $this->hasMany('App\Models\Task', 'category_id');
 }
}

So after that you can simply run most of queries of query builder through category model. And can utilized ORM in similar way as Moloquent supports many types of relationships, so you can utilize them too.

Moloquent Detail and Documentation:

Moloquent have very good examples at github to understand it and use it. So for Moloquent usage, reference and understanding, please check moloquent github page .

Installing Laravel on Windows

I wrote an article on Installing LAMP environment on ubuntu cloud instance that somebody found helpful and he requested me to write for Laravel installation and configuration for Windows development machine. So here is step by step guide.

XAMPP:

I assume you have XAMPP or equivalent installed and running. If not then download it from https://www.apachefriends.org/download.html

 Composer:

Then second thing you should have is composer. Composer is a dependency manager for PHP. To check if you already have composer installed, open command prompt and type following command and hit enter:

composer –version

If you see composer version then it is installed, but if you don’t see that and instead see:

‘composer’ is not recognized as an internal or external command, operable program or batch file

Then you need to install composer. So download and install composer by following steps from here: https://getcomposer.org/doc/00-intro.md#installation-windows

Installing Laravel via Composer:

We will install Laravel using composer. But first you need to switch to your www root directory.  For XAMPP it will be htdocs folder in your xampp directory.

Type following command in command prompt and hit enter:

composer create-project laravel/laravel --prefer-dist

This will start downloading laravel and its dependencies that may take few minutes.

And it is installed. To test it hit:

http://localhost/laravel/public/

And you should see Laravel welcome screen. Once you have Laravel installed and running, Laravel website has a good documentation that you can follow. And if you want even better source than that, Laracasts is the place to start.