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

Improving performance using the cache

The cache software design pattern is where you store a result that takes a long time to generate. This could take the form of a lengthy view script or a complex database query. The storage destination needs to be highly performant, of course, if you wish to improve the user experience of website visitors. As different installations will have different potential storage targets, the cache mechanism lends itself to the adapter pattern as well. Examples of potential storage destinations include memory, a database, and the filesystem.

How to do it...

  1. As with a couple of other recipes in this chapter, as there are shared constants, we define a discreet Application\Cache\Constants class:
    <?php
    namespace Application\Cache;
    
    class Constants
    {
      const DEFAULT_GROUP  = 'default';
      const DEFAULT_PREFIX = 'CACHE_';
      const DEFAULT_SUFFIX = '.cache';
      const ERROR_GET      = 'ERROR: unable to retrieve from cache';
      // not all constants are shown to conserve space
    }
  2. Seeing as we are following the adapter design pattern, we define an interface next:
    namespace Application\Cache;
    interface  CacheAdapterInterface
    {
      public function hasKey($key);
      public function getFromCache($key, $group);
      public function saveToCache($key, $data, $group);
      public function removeByKey($key);
      public function removeByGroup($group);
    }
  3. Now we are ready to define our first cache adapter, in this illustration, by using a MySQL database. We need to define properties that will hold column names as well as prepared statements:
    namespace Application\Cache;
    use PDO;
    use Application\Database\Connection;
    class Database implements CacheAdapterInterface
    {
      protected $sql;
      protected $connection;
      protected $table;
      protected $dataColumnName;
      protected $keyColumnName;
      protected $groupColumnName;
      protected $statementHasKey       = NULL;
      protected $statementGetFromCache = NULL;
      protected $statementSaveToCache  = NULL;
      protected $statementRemoveByKey  = NULL;
      protected $statementRemoveByGroup= NULL;
  4. The constructor allows us to provide key column names as well as an Application\Database\Connection instance and the name of the table used for the cache:
    public function __construct(Connection $connection,
      $table,
      $idColumnName,
      $keyColumnName,
      $dataColumnName,
      $groupColumnName = Constants::DEFAULT_GROUP)
      {
        $this->connection  = $connection;
        $this->setTable($table);
        $this->setIdColumnName($idColumnName);
        $this->setDataColumnName($dataColumnName);
        $this->setKeyColumnName($keyColumnName);
        $this->setGroupColumnName($groupColumnName);
      }
  5. The next few methods prepare statements, and are called when we access the database. We do not show all the methods, but present enough to give you the idea:
    public function prepareHasKey()
    {
      $sql = 'SELECT `' . $this->idColumnName . '` '
      . 'FROM `'   . $this->table . '` '
      . 'WHERE `'  . $this->keyColumnName . '` = :key ';
      $this->sql[__METHOD__] = $sql;
      $this->statementHasKey = 
      $this->connection->pdo->prepare($sql);
    }
    public function prepareGetFromCache()
    {
      $sql = 'SELECT `' . $this->dataColumnName . '` '
      . 'FROM `'   . $this->table . '` '
      . 'WHERE `'  . $this->keyColumnName . '` = :key '
      . 'AND `'    . $this->groupColumnName . '` = :group';
      $this->sql[__METHOD__] = $sql;
      $this->statementGetFromCache = 
      $this->connection->pdo->prepare($sql);
    }
  6. Now we define a method that determines whether data for a given key exists:
    public function hasKey($key)
    {
      $result = 0;
      try {
          if (!$this->statementHasKey) $this->prepareHasKey();
              $this->statementHasKey->execute(['key' => $key]);
      } catch (Throwable $e) {
          error_log(__METHOD__ . ':' . $e->getMessage());
          throw new Exception(Constants::ERROR_REMOVE_KEY);
      }
      return (int) $this->statementHasKey
      ->fetch(PDO::FETCH_ASSOC)[$this->idColumnName];
    }
  7. The core methods are ones that read from and write to the cache. Here is the method that retrieves from the cache. All we need to do is to execute the prepared statement, which performs a SELECT, with a WHERE clause, which incorporates the key and group:
    public function getFromCache(
    $key, $group = Constants::DEFAULT_GROUP)
    {
      try {
          if (!$this->statementGetFromCache) 
              $this->prepareGetFromCache();
              $this->statementGetFromCache->execute(
                ['key' => $key, 'group' => $group]);
              while ($row = $this->statementGetFromCache
                ->fetch(PDO::FETCH_ASSOC)) {
                if ($row && count($row)) {
                    yield unserialize($row[$this->dataColumnName]);
                }
              }
      } catch (Throwable $e) {
          error_log(__METHOD__ . ':' . $e->getMessage());
          throw new Exception(Constants::ERROR_GET);
      }
    }
  8. When writing to the cache, we first determine whether an entry for this cache key exists. If so, we perform an UPDATE; otherwise, we perform an INSERT:
    public function saveToCache($key, $data, $group = Constants::DEFAULT_GROUP)
    {
      $id = $this->hasKey($key);
      $result = 0;
      try {
          if ($id) {
              if (!$this->statementUpdateCache) 
                  $this->prepareUpdateCache();
                  $result = $this->statementUpdateCache
                  ->execute(['key' => $key, 
                  'data' => serialize($data), 
                  'group' => $group, 
                  'id' => $id]);
              } else {
                  if (!$this->statementSaveToCache) 
                  $this->prepareSaveToCache();
                  $result = $this->statementSaveToCache
                  ->execute(['key' => $key, 
                  'data' => serialize($data), 
                  'group' => $group]);
              }
          } catch (Throwable $e) {
              error_log(__METHOD__ . ':' . $e->getMessage());
              throw new Exception(Constants::ERROR_SAVE);
          }
          return $result;
       }
  9. We then define two methods that remove the cache either by key or by group. Removal by group provides a convenient mechanism if there are a large number of items that need to be deleted:
    public function removeByKey($key)
    {
      $result = 0;
      try {
          if (!$this->statementRemoveByKey) 
          $this->prepareRemoveByKey();
          $result = $this->statementRemoveByKey->execute(
            ['key' => $key]);
      } catch (Throwable $e) {
          error_log(__METHOD__ . ':' . $e->getMessage());
          throw new Exception(Constants::ERROR_REMOVE_KEY);
      }
      return $result;
    }
    
    public function removeByGroup($group)
    {
      $result = 0;
      try {
          if (!$this->statementRemoveByGroup) 
              $this->prepareRemoveByGroup();
              $result = $this->statementRemoveByGroup->execute(
                ['group' => $group]);
          } catch (Throwable $e) {
              error_log(__METHOD__ . ':' . $e->getMessage());
              throw new Exception(Constants::ERROR_REMOVE_GROUP);
          }
          return $result;
      }
  10. Lastly, we define getters and setters for each of the properties. Not all are shown here to conserve space:
    public function setTable($name)
    {
      $this->table = $name;
    }
    public function getTable()
    {
      return $this->table;
    }
    // etc.
    }
  11. The filesystem cache adapter defines the same methods as defined earlier. Note the use of md5(), not for security, but as a way of quickly generating a text string from the key:
    namespace Application\Cache;
    use RecursiveIteratorIterator;
    use RecursiveDirectoryIterator;
    class File implements CacheAdapterInterface
    {
      protected $dir;
      protected $prefix;
      protected $suffix;
      public function __construct(
        $dir, $prefix = NULL, $suffix = NULL)
      {
        if (!file_exists($dir)) {
            error_log(__METHOD__ . ':' . Constants::ERROR_DIR_NOT);
            throw new Exception(Constants::ERROR_DIR_NOT);
        }
        $this->dir = $dir;
        $this->prefix = $prefix ?? Constants::DEFAULT_PREFIX;
        $this->suffix = $suffix ?? Constants::DEFAULT_SUFFIX;
      }
    
      public function hasKey($key)
      {
        $action = function ($name, $md5Key, &$item) {
          if (strpos($name, $md5Key) !== FALSE) {
            $item ++;
          }
        };
    
        return $this->findKey($key, $action);
      }
    
      public function getFromCache($key, $group = Constants::DEFAULT_GROUP)
      {
        $fn = $this->dir . '/' . $group . '/' 
        . $this->prefix . md5($key) . $this->suffix;
        if (file_exists($fn)) {
            foreach (file($fn) as $line) { yield $line; }
        } else {
            return array();
        }
      }
    
      public function saveToCache(
        $key, $data, $group = Constants::DEFAULT_GROUP)
      {
        $baseDir = $this->dir . '/' . $group;
        if (!file_exists($baseDir)) mkdir($baseDir);
        $fn = $baseDir . '/' . $this->prefix . md5($key) 
        . $this->suffix;
        return file_put_contents($fn, json_encode($data));
      }
    
      protected function findKey($key, callable $action)
      {
        $md5Key = md5($key);
        $iterator = new RecursiveIteratorIterator(
          new RecursiveDirectoryIterator($this->dir),
          RecursiveIteratorIterator::SELF_FIRST);
          $item = 0;
        foreach ($iterator as $name => $obj) {
          $action($name, $md5Key, $item);
        }
        return $item;
      }
    
      public function removeByKey($key)
      {
        $action = function ($name, $md5Key, &$item) {
          if (strpos($name, $md5Key) !== FALSE) {
            unlink($name);
            $item++;
          }
        };
        return $this->findKey($key, $action);
      }
    
      public function removeByGroup($group)
      {
        $removed = 0;
        $baseDir = $this->dir . '/' . $group;
        $pattern = $baseDir . '/' . $this->prefix . '*' 
        . $this->suffix;
        foreach (glob($pattern) as $file) {
          unlink($file);
          $removed++;
        }
        return $removed;
      }
    }
  12. Now we are ready to present the core cache mechanism. In the constructor, we accept a class that implements CacheAdapterInterface as an argument:
    namespace Application\Cache;
    use Psr\Http\Message\RequestInterface;
    use Application\MiddleWare\ { Request, Response, TextStream };
    class Core
    {
      public function __construct(CacheAdapterInterface $adapter)
      {
        $this->adapter = $adapter;
      }
  13. Next are a series of wrapper methods that call methods of the same name from the adapter, but accept a Psr\Http\Message\RequestInterface class an an argument, and return a Psr\Http\Message\ResponseInterface as a response. We start with a simple one: hasKey(). Note how we extract the key from the request parameters:
    public function hasKey(RequestInterface $request)
    {
      $key = $request->getUri()->getQueryParams()['key'] ?? '';
      $result = $this->adapter->hasKey($key);
    }
  14. To retrieve information from the cache, we need to pull the key and group parameters from the request object, and then call the same method from the adapter. If no results are obtained, we set a 204 code, which indicates the request was a success, but no content was produced. Otherwise, we set a 200 (success) code, and iterate through the results. Everything is then stuffed into a response object, which is returned:
    public function getFromCache(RequestInterface $request)
    {
      $text = array();
      $key = $request->getUri()->getQueryParams()['key'] ?? '';
      $group = $request->getUri()->getQueryParams()['group'] 
        ?? Constants::DEFAULT_GROUP;
      $results = $this->adapter->getFromCache($key, $group);
      if (!$results) { 
          $code = 204; 
      } else {
          $code = 200;
          foreach ($results as $line) $text[] = $line;
      }
      if (!$text || count($text) == 0) $code = 204;
      $body = new TextStream(json_encode($text));
      return (new Response())->withStatus($code)
                             ->withBody($body);
    }
  15. Strangely, writing to the cache is almost identical, except that the results are expected to be either a number (that is, the number of rows affected), or a Boolean result:
    public function saveToCache(RequestInterface $request)
    {
      $text = array();
      $key = $request->getUri()->getQueryParams()['key'] ?? '';
      $group = $request->getUri()->getQueryParams()['group'] 
        ?? Constants::DEFAULT_GROUP;
      $data = $request->getBody()->getContents();
      $results = $this->adapter->saveToCache($key, $data, $group);
      if (!$results) { 
          $code = 204;
      } else {
          $code = 200;
          $text[] = $results;
      }
          $body = new TextStream(json_encode($text));
          return (new Response())->withStatus($code)
                                 ->withBody($body);
      }
  16. The remove methods are, as expected, quite similar to each other:
    public function removeByKey(RequestInterface $request)
    {
      $text = array();
      $key = $request->getUri()->getQueryParams()['key'] ?? '';
      $results = $this->adapter->removeByKey($key);
      if (!$results) {
          $code = 204;
      } else {
          $code = 200;
          $text[] = $results;
      }
      $body = new TextStream(json_encode($text));
      return (new Response())->withStatus($code)
                             ->withBody($body);
    }
    
    public function removeByGroup(RequestInterface $request)
    {
      $text = array();
      $group = $request->getUri()->getQueryParams()['group'] 
        ?? Constants::DEFAULT_GROUP;
      $results = $this->adapter->removeByGroup($group);
      if (!$results) {
          $code = 204;
      } else {
          $code = 200;
          $text[] = $results;
      }
      $body = new TextStream(json_encode($text));
      return (new Response())->withStatus($code)
                             ->withBody($body);
      }
    } // closing brace for class Core

How it works...

In order to demonstrate the use of the Acl class, you will need to define the classes described in this recipe, summarized here:

Class

Discussed in these steps

Application\Cache\Constants

1

Application\Cache\CacheAdapterInterface

2

Application\Cache\Database

3 - 10

Application\Cache\File

11

Application\Cache\Core

12 - 16

Next, define a test program, which you could call chap_09_middleware_cache_db.php. In this program, as usual, define constants for necessary files, set up autoloading, use the appropriate classes, oh... and write a function that produces prime numbers (you're probably re-reading that last little bit at this point. Not to worry, we can help you with that!):

<?php
define('DB_CONFIG_FILE', __DIR__ . '/../config/db.config.php');
define('DB_TABLE', 'cache');
define('CACHE_DIR', __DIR__ . '/cache');
define('MAX_NUM', 100000);
require __DIR__ . '/../Application/Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__ . '/..');
use Application\Database\Connection;
use Application\Cache\{ Constants, Core, Database, File };
use Application\MiddleWare\ { Request, TextStream };

Well, a function that takes a long time to run is needed, so prime number generator, here we go! The numbers 1, 2, and 3 are given as primes. We use the PHP 7 yield from syntax to produce these first three. then, we skip right to 5, and proceed up to the maximum value requested:

function generatePrimes($max)
{
  yield from [1,2,3];
  for ($x = 5; $x < $max; $x++)
  {
    if($x & 1) {
        $prime = TRUE;
        for($i = 3; $i < $x; $i++) {
            if(($x % $i) === 0) {
                $prime = FALSE;
                break;
            }
        }
        if ($prime) yield $x;
    }
  }
}

You can then set up a database cache adapter instance, which serves as an argument for the core:

$conn    = new Connection(include DB_CONFIG_FILE);
$dbCache = new Database(
  $conn, DB_TABLE, 'id', 'key', 'data', 'group');
$core    = new Core($dbCache);

Alternatively, if you wish to use the file cache adapter instead, here is the appropriate code:

$fileCache = new File(CACHE_DIR);
$core    = new Core($fileCache);

If you wanted to clear the cache, here is how it might be done:

$uriString = '/?group=' . Constants::DEFAULT_GROUP;
$cacheRequest = new Request($uriString, 'get');
$response = $core->removeByGroup($cacheRequest);

You can use time() and microtime() to see how long this script runs with and without the cache:

$start = time() + microtime(TRUE);
echo "\nTime: " . $start;

Next, generate a cache request. A status code of 200 indicates you were able to obtain a list of primes from the cache:

$uriString = '/?key=Test1';
$cacheRequest = new Request($uriString, 'get');
$response = $core->getFromCache($cacheRequest);
$status   = $response->getStatusCode();
if ($status == 200) {
    $primes = json_decode($response->getBody()->getContents());

Otherwise, you can assume nothing was obtained from the cache, which means you need to generate prime numbers, and save the results to the cache:

} else {
    $primes = array();
    foreach (generatePrimes(MAX_NUM) as $num) {
        $primes[] = $num;
    }
    $body = new TextStream(json_encode($primes));
    $response = $core->saveToCache(
    $cacheRequest->withBody($body));
}

You can then check the stop time, calculate the difference, and have a look at your new list of primes:

$time = time() + microtime(TRUE);
$diff = $time - $start;
echo "\nTime: $time";
echo "\nDifference: $diff";
var_dump($primes);

Here is the expected output before values were stored in the cache:

How it works...

You can now run the same program again, this time retrieving from the cache:

How it works...

Allowing for the fact that our little prime number generator is not the world's most efficient, and also that the demonstration was run on a laptop, the time went from over 30 seconds down to milliseconds.

There's more...

Another possible cache adapter could be built around commands that are part of the Alternate PHP Cache (APC) extension. This extension includes such functions as apc_exists(), apc_store(), apc_fetch(), and apc_clear_cache(). These functions are perfect for our hasKey(), saveToCache(), getFromCache(), and removeBy*() functions.

See also

You might consider making slight changes to the cache adapter classes described previously following PSR-6, which is a standards recommendation directed towards the cache. There is not the same level of acceptance of this standard as with PSR-7, however, so we decided to not follow this standard exactly in the recipe presented here. For more information on PSR-6, please refer to http://www.php-fig.org/psr/psr-6/.