Table of Contents for
PHP 7: Real World Application Development

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition PHP 7: Real World Application Development by Branko Ajzele Published by Packt Publishing, 2016
  1. Cover
  2. Table of Contents
  3. PHP 7: Real World Application Development
  4. PHP 7: Real World Application Development
  5. PHP 7: Real World Application Development
  6. Credits
  7. Preface
  8. What you need for this learning path
  9. Who this learning path is for
  10. Reader feedback
  11. Customer support
  12. 1. Module 1
  13. 1. Building a Foundation
  14. PHP 7 installation considerations
  15. Using the built-in PHP web server
  16. Defining a test MySQL database
  17. Installing PHPUnit
  18. Implementing class autoloading
  19. Hoovering a website
  20. Building a deep web scanner
  21. Creating a PHP 5 to PHP 7 code converter
  22. 2. Using PHP 7 High Performance Features
  23. Understanding the abstract syntax tree
  24. Understanding differences in parsing
  25. Understanding differences in foreach() handling
  26. Improving performance using PHP 7 enhancements
  27. Iterating through a massive file
  28. Uploading a spreadsheet into a database
  29. Recursive directory iterator
  30. 3. Working with PHP Functions
  31. Developing functions
  32. Hinting at data types
  33. Using return value data typing
  34. Using iterators
  35. Writing your own iterator using generators
  36. 4. Working with PHP Object-Oriented Programming
  37. Developing classes
  38. Extending classes
  39. Using static properties and methods
  40. Using namespaces
  41. Defining visibility
  42. Using interfaces
  43. Using traits
  44. Implementing anonymous classes
  45. 5. Interacting with a Database
  46. Using PDO to connect to a database
  47. Building an OOP SQL query builder
  48. Handling pagination
  49. Defining entities to match database tables
  50. Tying entity classes to RDBMS queries
  51. Embedding secondary lookups into query results
  52. Implementing jQuery DataTables PHP lookups
  53. 6. Building Scalable Websites
  54. Creating a generic form element generator
  55. Creating an HTML radio element generator
  56. Creating an HTML select element generator
  57. Implementing a form factory
  58. Chaining $_POST filters
  59. Chaining $_POST validators
  60. Tying validation to a form
  61. 7. Accessing Web Services
  62. Converting between PHP and XML
  63. Creating a simple REST client
  64. Creating a simple REST server
  65. Creating a simple SOAP client
  66. Creating a simple SOAP server
  67. 8. Working with Date/Time and International Aspects
  68. Using emoticons or emoji in a view script
  69. Converting complex characters
  70. Getting the locale from browser data
  71. Formatting numbers by locale
  72. Handling currency by locale
  73. Formatting date/time by locale
  74. Creating an HTML international calendar generator
  75. Building a recurring events generator
  76. Handling translation without gettext
  77. 9. Developing Middleware
  78. Authenticating with middleware
  79. Using middleware to implement access control
  80. Improving performance using the cache
  81. Implementing routing
  82. Making inter-framework system calls
  83. Using middleware to cross languages
  84. 10. Looking at Advanced Algorithms
  85. Using getters and setters
  86. Implementing a linked list
  87. Building a bubble sort
  88. Implementing a stack
  89. Building a binary search class
  90. Implementing a search engine
  91. Displaying a multi-dimensional array and accumulating totals
  92. 11. Implementing Software Design Patterns
  93. Creating an array to object hydrator
  94. Building an object to array hydrator
  95. Implementing a strategy pattern
  96. Defining a mapper
  97. Implementing object-relational mapping
  98. Implementing the Pub/Sub design pattern
  99. 12. Improving Web Security
  100. Filtering $_POST data
  101. Validating $_POST data
  102. Safeguarding the PHP session
  103. Securing forms with a token
  104. Building a secure password generator
  105. Safeguarding forms with a CAPTCHA
  106. Encrypting/decrypting without mcrypt
  107. 13. Best Practices, Testing, and Debugging
  108. Using Traits and Interfaces
  109. Universal exception handler
  110. Universal error handler
  111. Writing a simple test
  112. Writing a test suite
  113. Generating fake test data
  114. Customizing sessions using session_start parameters
  115. A. Defining PSR-7 Classes
  116. Implementing PSR-7 value object classes
  117. Developing a PSR-7 Request class
  118. Defining a PSR-7 Response class
  119. 2. Module 2
  120. 1. Setting Up the Environment
  121. Setting up Debian or Ubuntu
  122. Setting up CentOS
  123. Setting up Vagrant
  124. Summary
  125. 2. New Features in PHP 7
  126. New operators
  127. Uniform variable syntax
  128. Miscellaneous features and changes
  129. Summary
  130. 3. Improving PHP 7 Application Performance
  131. HTTP server optimization
  132. HTTP persistent connection
  133. Content Delivery Network (CDN)
  134. CSS and JavaScript optimization
  135. Full page caching
  136. Varnish
  137. The infrastructure
  138. Summary
  139. 4. Improving Database Performance
  140. Storage engines
  141. The Percona Server - a fork of MySQL
  142. MySQL performance monitoring tools
  143. Percona XtraDB Cluster (PXC)
  144. Redis – the key-value cache store
  145. Memcached key-value cache store
  146. Summary
  147. 5. Debugging and Profiling
  148. Profiling with Xdebug
  149. PHP DebugBar
  150. Summary
  151. 6. Stress/Load Testing PHP Applications
  152. ApacheBench (ab)
  153. Siege
  154. Load testing real-world applications
  155. Summary
  156. 7. Best Practices in PHP Programming
  157. Test-driven development (TDD)
  158. Design patterns
  159. Service-oriented architecture (SOA)
  160. Being object-oriented and reusable always
  161. PHP frameworks
  162. Version control system (VCS) and Git
  163. Deployment and Continuous Integration (CI)
  164. Summary
  165. A. Tools to Make Life Easy
  166. Git – A version control system
  167. Grunt watch
  168. Summary
  169. B. MVC and Frameworks
  170. Laravel
  171. Lumen
  172. Apigility
  173. Summary
  174. 3. Module 3
  175. 1. Ecosystem Overview
  176. Summary
  177. 2. GoF Design Patterns
  178. Structural patterns
  179. Behavioral patterns
  180. Summary
  181. 3. SOLID Design Principles
  182. Open/closed principle
  183. Liskov substitution principle
  184. Interface Segregation Principle
  185. Dependency inversion principle
  186. Summary
  187. 4. Requirement Specification for a Modular Web Shop App
  188. Wireframing
  189. Defining a technology stack
  190. Summary
  191. 5. Symfony at a Glance
  192. Creating a blank project
  193. Using Symfony console
  194. Controller
  195. Routing
  196. Templates
  197. Forms
  198. Configuring Symfony
  199. The bundle system
  200. Databases and Doctrine
  201. Testing
  202. Validation
  203. Summary
  204. 6. Building the Core Module
  205. Dependencies
  206. Implementation
  207. Unit testing
  208. Functional testing
  209. Summary
  210. 7. Building the Catalog Module
  211. Dependencies
  212. Implementation
  213. Unit testing
  214. Functional testing
  215. Summary
  216. 8. Building the Customer Module
  217. Dependencies
  218. Implementation
  219. Unit testing
  220. Functional testing
  221. Summary
  222. 9. Building the Payment Module
  223. Dependencies
  224. Implementation
  225. Unit testing
  226. Functional testing
  227. Summary
  228. 10. Building the Shipment Module
  229. Dependencies
  230. Implementation
  231. Unit testing
  232. Functional testing
  233. Summary
  234. 11. Building the Sales Module
  235. Dependencies
  236. Implementation
  237. Unit testing
  238. Functional testing
  239. Summary
  240. 12. Integrating and Distributing Modules
  241. Understanding GitHub
  242. Understanding Composer
  243. Understanding Packagist
  244. Summary
  245. Bibliography
  246. Index

Creating a simple REST server

There are several considerations when implementing a REST server. The answers to these three questions will then let you define your REST service:

  • How is the raw request captured?
  • What Application Programming Interface (API) do you want to publish?
  • How do you plan to map HTTP verbs (for example, GET, PUT, POST, and DELETE) to API methods?

How to do it...

  1. We will implement our REST server by building onto the request and response classes defined in the previous recipe, Creating a simple REST client. Review the classes discussed in the previous recipe, including the following:
    • Application\Web\AbstractHttp
    • Application\Web\Request
    • Application\Web\Received
  2. We will also need to define a formal Application\Web\Response response class, based on AbstractHttp. The primary difference between this class and the others is that it accepts an instance of Application\Web\Request as an argument. The primary work is accomplished in the __construct() method. It's also important to set the Content-Type header and status:
    namespace Application\Web;
    class Response extends AbstractHttp
    {
    
      public function __construct(Request $request = NULL, 
                                  $status = NULL, $contentType = NULL)
      {
        if ($request) {
          $this->uri = $request->getUri();
          $this->data = $request->getData();
          $this->method = $request->getMethod();
          $this->cookies = $request->getCookies();
          $this->setTransport();
        }
        $this->processHeaders($contentType);
        if ($status) {
          $this->setStatus($status);
        }
      }
      protected function processHeaders($contentType)
      {
        if (!$contentType) {
          $this->setHeaderByKey(self::HEADER_CONTENT_TYPE, 
            self::CONTENT_TYPE_JSON);
        } else {
          $this->setHeaderByKey(self::HEADER_CONTENT_TYPE, 
            $contentType);
        }
      }
      public function setStatus($status)
      {
        $this->status = $status;
      }
      public function getStatus()
      {
        return $this->status;
      }
    }
  3. We are now in a position to define the Application\Web\Rest\Server class. You may be surprised at how simple it is. The real work is done in the associated API class:

    Note

    Note the use of the PHP 7 group use syntax:

    use Application\Web\ { Request,Response,Received }
    namespace Application\Web\Rest;
    use Application\Web\ { Request, Response, Received };
    class Server
    {
      protected $api;
      public function __construct(ApiInterface $api)
      {
        $this->api = $api;
      }
  4. Next, we define a listen() method that serves as a target for the request. The heart of the server implementation is this line of code:
    $jsonData = json_decode(file_get_contents('php://input'),true);
  5. This captures raw input, which is assumed to be in JSON format:
    public function listen()
    {
      $request  = new Request();
      $response = new Response($request);
      $getPost  = $_REQUEST ?? array();
      $jsonData = json_decode(
        file_get_contents('php://input'),true);
      $jsonData = $jsonData ?? array();
      $request->setData(array_merge($getPost,$jsonData));

    Note

    We have also added a provision for authentication. Otherwise, anybody could make requests and obtain potentially sensitive data. You will note that we do not have the server class performing authentication; rather, we leave it to the API class:

    if (!$this->api->authenticate($request)) {
        $response->setStatus(Request::STATUS_401);
        echo $this->api::ERROR;
        exit;
    }
  6. We then map API methods to the primary HTTP methods GET, PUT, POST,and DELETE:
    $id = $request->getData()[$this->api::ID_FIELD] ?? NULL;
    switch (strtoupper($request->getMethod())) {
      case Request::METHOD_POST :
        $this->api->post($request, $response);
        break;
      case Request::METHOD_PUT :
        $this->api->put($request, $response);
        break;
      case Request::METHOD_DELETE :
        $this->api->delete($request, $response);
        break;
      case Request::METHOD_GET :
      default :
        // return all if no params
      $this->api->get($request, $response);
    }
  7. Finally, we package the response and send it out, JSON-encoded:
      $this->processResponse($response);
      echo json_encode($response->getData());
    }
  8. The processResponse() method sets headers and makes sure the result is packaged as an Application\Web\Response object:
    protected function processResponse($response)
    {
      if ($response->getHeaders()) {
        foreach ($response->getHeaders() as $key => $value) {
          header($key . ': ' . $value, TRUE, 
                 $response->getStatus());
        }
      }        
      header(Request::HEADER_CONTENT_TYPE 
      . ': ' . Request::CONTENT_TYPE_JSON, TRUE);
      if ($response->getCookies()) {
        foreach ($response->getCookies() as $key => $value) {
          setcookie($key, $value);
        }
      }
    }
  9. As mentioned earlier, the real work is done by the API class. We start by defining an abstract class that ensures the primary methods get(), put(), and so on are represented, and that all such methods accept request and response objects as arguments. You might notice that we have added a generateToken() method that uses the PHP 7 random_bytes() function to generate a truly random series of 16 bytes:
    namespace Application\Web\Rest;
    use Application\Web\ { Request, Response };
    abstract class AbstractApi implements ApiInterface
    {
      const TOKEN_BYTE_SIZE  = 16;
      protected $registeredKeys;
      abstract public function get(Request $request, 
                                   Response $response);
      abstract public function put(Request $request, 
                                   Response $response);
      abstract public function post(Request $request, 
                                    Response $response);
      abstract public function delete(Request $request, 
                                      Response $response);
      abstract public function authenticate(Request $request);
      public function __construct($registeredKeys, $tokenField)
      {
        $this->registeredKeys = $registeredKeys;
      }
      public static function generateToken()
      {
        return bin2hex(random_bytes(self::TOKEN_BYTE_SIZE));    
      }
    }
  10. We also define a corresponding interface that can be used for architectural and design purposes, as well as code development control:
    namespace Application\Web\Rest;
    use Application\Web\ { Request, Response };
    interface ApiInterface
    {
      public function get(Request $request, Response $response);
      public function put(Request $request, Response $response);
      public function post(Request $request, Response $response);
      public function delete(Request $request, Response $response);
      public function authenticate(Request $request);
    }
  11. Here, we present a sample API based on AbstractApi. This class leverages database classes defined in Chapter 5, Interacting with a Database:
    namespace Application\Web\Rest;
    use Application\Web\ { Request, Response, Received };
    use Application\Entity\Customer;
    use Application\Database\ { Connection, CustomerService };
    
    class CustomerApi extends AbstractApi
    {
      const ERROR = 'ERROR';
      const ERROR_NOT_FOUND = 'ERROR: Not Found';
      const SUCCESS_UPDATE = 'SUCCESS: update succeeded';
      const SUCCESS_DELETE = 'SUCCESS: delete succeeded';
      const ID_FIELD = 'id';      // field name of primary key
      const TOKEN_FIELD = 'token';  // field used for authentication
      const LIMIT_FIELD = 'limit';
      const OFFSET_FIELD = 'offset';
      const DEFAULT_LIMIT = 20;
      const DEFAULT_OFFSET = 0;
          
      protected $service;
          
      public function __construct($registeredKeys, 
                                  $dbparams, $tokenField = NULL)
      {
        parent::__construct($registeredKeys, $tokenField);
        $this->service = new CustomerService(
          new Connection($dbparams));
      }
  12. All methods receive request and response as arguments. You will notice the use of getDataByKey() to retrieve data items. The actual database interaction is performed by the service class. You might also notice that in all cases, we set an HTTP status code to inform the client of success or failure. In the case of get(), we look for an ID parameter. If received, we deliver information on a single customer only. Otherwise, we deliver a list of all customers using limit and offset:
    public function get(Request $request, Response $response)
    {
      $result = array();
      $id = $request->getDataByKey(self::ID_FIELD) ?? 0;
      if ($id > 0) {
          $result = $this->service->
            fetchById($id)->entityToArray();  
      } else {
        $limit  = $request->getDataByKey(self::LIMIT_FIELD) 
          ?? self::DEFAULT_LIMIT;
        $offset = $request->getDataByKey(self::OFFSET_FIELD) 
          ?? self::DEFAULT_OFFSET;
        $result = [];
        $fetch = $this->service->fetchAll($limit, $offset);
        foreach ($fetch as $row) {
          $result[] = $row;
        }
      }
      if ($result) {
          $response->setData($result);
          $response->setStatus(Request::STATUS_200);
      } else {
          $response->setData([self::ERROR_NOT_FOUND]);
          $response->setStatus(Request::STATUS_500);
      }
    }
  13. The put() method is used to insert customer data:
    public function put(Request $request, Response $response)
    {
      $cust = Customer::arrayToEntity($request->getData(), 
                                      new Customer());
      if ($newCust = $this->service->save($cust)) {
          $response->setData(['success' => self::SUCCESS_UPDATE, 
                              'id' => $newCust->getId()]);
          $response->setStatus(Request::STATUS_200);
      } else {
          $response->setData([self::ERROR]);
          $response->setStatus(Request::STATUS_500);
      }      
    }
  14. The post() method is used to update existing customer entries:
    public function post(Request $request, Response $response)
    {
      $id = $request->getDataByKey(self::ID_FIELD) ?? 0;
      $reqData = $request->getData();
      $custData = $this->service->
        fetchById($id)->entityToArray();
      $updateData = array_merge($custData, $reqData);
      $updateCust = Customer::arrayToEntity($updateData, 
      new Customer());
      if ($this->service->save($updateCust)) {
          $response->setData(['success' => self::SUCCESS_UPDATE, 
                              'id' => $updateCust->getId()]);
          $response->setStatus(Request::STATUS_200);
      } else {
          $response->setData([self::ERROR]);
          $response->setStatus(Request::STATUS_500);
      }      
    }
  15. As the name implies, delete() removes a customer entry:
    public function delete(Request $request, Response $response)
    {
      $id = $request->getDataByKey(self::ID_FIELD) ?? 0;
      $cust = $this->service->fetchById($id);
      if ($cust && $this->service->remove($cust)) {
          $response->setData(['success' => self::SUCCESS_DELETE, 
                              'id' => $id]);
          $response->setStatus(Request::STATUS_200);
      } else {
          $response->setData([self::ERROR_NOT_FOUND]);
          $response->setStatus(Request::STATUS_500);
      }
    }
  16. Finally, we define authenticate() to provide, in this example, a low-level mechanism to protect API usage:
    public function authenticate(Request $request)
    {
      $authToken = $request->getDataByKey(self::TOKEN_FIELD) 
        ?? FALSE;
      if (in_array($authToken, $this->registeredKeys, TRUE)) {
          return TRUE;
      } else {
          return FALSE;
      }
    }
    }

How it works...

Define the following classes, which were discussed in the previous recipe:

  • Application\Web\AbstractHttp
  • Application\Web\Request
  • Application\Web\Received

You can then define the following classes, described in this recipe, summarized in this table:

Class Application\Web\*

Discussed in these steps

Response

2

Rest\Server

3 - 8

Rest\AbstractApi

9

Rest\ApiInterface

10

Rest\CustomerApi

11 - 16

You are now free to develop your own API class. If you choose to follow the illustration Application\Web\Rest\CustomerApi, however, you will need to also be sure to implement these classes, covered in Chapter 5, Interacting with a Database:

  • Application\Entity\Customer
  • Application\Database\Connection
  • Application\Database\CustomerService

You can now define a chap_07_simple_rest_server.php script that invokes the REST server:

<?php
$dbParams = include __DIR__ .  '/../../config/db.config.php';
require __DIR__ . '/../Application/Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__ . '/..');
use Application\Web\Rest\Server;
use Application\Web\Rest\CustomerApi;
$apiKey = include __DIR__ . '/api_key.php';
$server = new Server(new CustomerApi([$apiKey], $dbParams, 'id'));
$server->listen();

You can then use the built-in PHP 7 development server to listen on port 8080 for REST requests:

php -S localhost:8080 chap_07_simple_rest_server.php 

To test your API, use the Application\Web\Rest\AbstractApi::generateToken() method to generate an authentication token that you can place in an api_key.php file, something like this:

<?php return '79e9b5211bbf2458a4085707ea378129';

You can then use a generic API client (such as the one described in the previous recipe), or a browser plugin such as RESTClient by Chao Zhou (see http://restclient.net/ for more information) to generate sample requests. Make sure you include the token for your request, otherwise the API as defined will reject the request.

Here is an example of a POST request for ID 1, which sets the balance field to a value of 888888:

How it works...

There's more...

There are a number of libraries that help you implement a REST server. One of my favorites is an example implementing a REST server in a single file: https://www.leaseweb.com/labs/2015/10/creating-a-simple-rest-api-in-php/

Various frameworks, such as CodeIgniter and Zend Framework, also have REST server implementations.