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

Implementing object-relational mapping

There are two primary techniques to achieve a relational mapping between objects. The first technique involves pre-loading the related child objects into the parent object. The advantage to this approach is that it is easy to implement, and all parent-child information is immediately available. The disadvantage is that large amounts of memory are potentially consumed, and the performance curve is skewed.

The second technique is to embed a secondary lookup into the parent object. In this latter approach, when you need to access the child objects, you would run a getter that would perform the secondary lookup. The advantage of this approach is that performance demands are spread out throughout the request cycle, and memory usage is (or can be) more easily managed. The disadvantage of this approach is that there are more queries generated, which means more work for the database server.

Note

Please note, however, that we will show how the use of prepared statements can be used to greatly offset this disadvantage.

How to do it...

Let's have a look at two techniques to implement object-relational mapping.

Technique #1 - pre-loading all child information

First, we will discuss how to implement object relational mapping by pre-loading all child information into the parent class. For this illustration, we will use three related database tables, customer, purchases, and products:

  1. We will use the existing Application\Entity\Customer class (defined in Chapter 5, Interacting with a Database, in the Defining entity classes to match database tables recipe) as a model to develop an Application\Entity\Purchase class. As before, we will use the database definition as the basis of the entity class definition. Here is the database definition for the purchases table:
    CREATE TABLE `purchases` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `transaction` varchar(8) NOT NULL,
      `date` datetime NOT NULL,
      `quantity` int(10) unsigned NOT NULL,
      `sale_price` decimal(8,2) NOT NULL,
      `customer_id` int(11) DEFAULT NULL,
      `product_id` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `IDX_C3F3` (`customer_id`),
      KEY `IDX_665A` (`product_id`),
      CONSTRAINT `FK_665A` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`),
      CONSTRAINT `FK_C3F3` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`)
    );
  2. Based on the customer entity class, here is how Application\Entity\Purchase might look. Note that not all getters and setters are shown:
    namespace Application\Entity;
    
    class Purchase extends Base
    {
    
      const TABLE_NAME = 'purchases';
      protected $transaction = '';
      protected $date = NULL;
      protected $quantity = 0;
      protected $salePrice = 0.0;
      protected $customerId = 0;
      protected $productId = 0;
    
      protected $mapping = [
        'id'            => 'id',
        'transaction'   => 'transaction',
        'date'          => 'date',
        'quantity'      => 'quantity',
        'sale_price'    => 'salePrice',
        'customer_id'   => 'customerId',
        'product_id'    => 'productId',
      ];
    
      public function getTransaction() : string
      {
        return $this->transaction;
      }
      public function setTransaction($transaction)
      {
        $this->transaction = $transaction;
      }
      // NOTE: other getters / setters are not shown here
    }
  3. We are now ready to define Application\Entity\Product. Here is the database definition for the products table:
    CREATE TABLE `products` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `sku` varchar(16) DEFAULT NULL,
      `title` varchar(255) NOT NULL,
      `description` varchar(4096) DEFAULT NULL,
      `price` decimal(10,2) NOT NULL,
      `special` int(11) NOT NULL,
      `link` varchar(128) NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `UNIQ_38C4` (`sku`)
    );
  4. Based on the customer entity class, here is how Application\Entity\Product might look:
    namespace Application\Entity;
    
    class Product extends Base
    {
    
      const TABLE_NAME = 'products';
      protected $sku = '';
      protected $title = '';
      protected $description = '';
      protected $price = 0.0;
      protected $special = 0;
      protected $link = '';
    
      protected $mapping = [
        'id'          => 'id',
        'sku'         => 'sku',
        'title'       => 'title',
        'description' => 'description',
        'price'       => 'price',
        'special'     => 'special',
        'link'        => 'link',
      ];
    
      public function getSku() : string
      {
        return $this->sku;
      }
      public function setSku($sku)
      {
        $this->sku = $sku;
      }
      // NOTE: other getters / setters are not shown here
    }
  5. Next, we need to implement a way to embed related objects. We will start with the Application\Entity\Customer parent class. For this section, we will assume the following relationships, illustrated in the following diagram:
    • One customer, many purchases
    • One purchase, one product
    Technique #1 - pre-loading all child information
  6. Accordingly, we define a getter and setter that process purchases in the form of an array of objects:
    protected $purchases = array();
    public function addPurchase($purchase)
    {
      $this->purchases[] = $purchase;
    }
    public function getPurchases()
    {
      return $this->purchases;
    }
  7. Now we turn our attention to Application\Entity\Purchase. In this case, there is a 1:1 relationship between a purchase and a product, so there's no need to process an array:
    protected $product = NULL;
    public function getProduct()
    {
      return $this->product;
    }
    public function setProduct(Product $product)
    {
      $this->product = $product;
    }

    Note

    Notice that in both entity classes, we do not alter the $mapping array. This is because implementing object relational mapping has no bearing on the mapping between entity property names and database column names.

  8. Since the core functionality of obtaining basic customer information is still needed, all we need to do is to extend the Application\Database\CustomerService class described in Chapter 5, Interacting with a Database, in the Tying entity classes to RDBMS queries recipe. We can create a new Application\Database\CustomerOrmService_1 class, which extends Application\Database\CustomerService:
    namespace Application\Database;
    use PDO;
    use PDOException;
    use Application\Entity\Customer;
    use Application\Entity\Product;
    use Application\Entity\Purchase;
    class CustomerOrmService_1 extends CustomerService
    {
      // add methods here
    }
  9. We then add a method to the new service class that performs a lookup and embeds the results, in the form of Product and Purchase entities, into the core customer entity. This method performs a lookup in the form of a JOIN. This is possible because there is a 1:1 relationship between purchase and product. Because the id column has the same name in both tables, we need to add the purchase ID column as an alias. We then loop through the results, creating Product and Purchase entities. After overriding the ID, we can then embed the Product entity into the Purchase entity, and then add the Purchase entity to the array in the Customer entity:
    protected function fetchPurchasesForCustomer(Customer $cust)
    {
      $sql = 'SELECT u.*,r.*,u.id AS purch_id '
        . 'FROM purchases AS u '
        . 'JOIN products AS r '
        . 'ON r.id = u.product_id '
        . 'WHERE u.customer_id = :id '
        . 'ORDER BY u.date';
      $stmt = $this->connection->pdo->prepare($sql);
      $stmt->execute(['id' => $cust->getId()]);
      while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $product = Product::arrayToEntity($result, new Product());
        $product->setId($result['product_id']);
        $purch = Purchase::arrayToEntity($result, new Purchase());
        $purch->setId($result['purch_id']);
        $purch->setProduct($product);
        $cust->addPurchase($purch);
      }
      return $cust;
    }
  10. Next, we provide a wrapper for the original fetchById() method. This block of code needs to not only get the original Customer entity, but needs to look up and embed Product and Purchase entities. We can call the new fetchByIdAndEmbedPurchases() method and accept a customer ID as an argument:
    public function fetchByIdAndEmbedPurchases($id)
    {
      return $this->fetchPurchasesForCustomer(
        $this->fetchById($id));
    }

Technique #2 - embedding secondary lookups

Now we will cover embedding secondary lookups into the related entity classes. We will continue to use the same illustration as above, using the entity classes defined that correspond to three related database tables, customer, purchases, and products:

  1. The mechanics of this approach are quite similar to those described in the preceding section. The main difference is that instead of doing the database lookup, and producing entity classes right away, we will embed a series of anonymous functions that will do the same thing, but called from the view logic.
  2. We need to add a new method to the Application\Entity\Customer class that adds a single entry to the purchases property. Instead of an array of Purchase entities, we will be supplying an anonymous function:
    public function setPurchases(Closure $purchaseLookup)
    {
      $this->purchases = $purchaseLookup;
    }
  3. Next, we will make a copy of the Application\Database\CustomerOrmService_1 class, and call it Application\Database\CustomerOrmService_2:
    namespace Application\Database;
    use PDO;
    use PDOException;
    use Application\Entity\Customer;
    use Application\Entity\Product;
    use Application\Entity\Purchase;
    class CustomerOrmService_2 extends CustomerService
    {
      // code
    }
  4. We then define a fetchPurchaseById() method, which looks up a single purchase based on its ID and produces a Purchase entity. Because we will ultimately be making a series of repetitive requests for single purchases in this approach, we can regain database efficiency by working off the same prepared statement, in this case, a property called $purchPreparedStmt:
    public function fetchPurchaseById($purchId)
    {
      if (!$this->purchPreparedStmt) {
          $sql = 'SELECT * FROM purchases WHERE id = :id';
          $this->purchPreparedStmt = 
          $this->connection->pdo->prepare($sql);
      }
      $this->purchPreparedStmt->execute(['id' => $purchId]);
      $result = $this->purchPreparedStmt->fetch(PDO::FETCH_ASSOC);
      return Purchase::arrayToEntity($result, new Purchase());
    }
  5. After that, we need a fetchProductById() method that looks up a single product based on its ID and produces a Product entity. Given that a customer may have purchased the same product several times, we can introduce an additional level of efficiency by storing acquired product entities in a $products array. In addition, as with purchases, we can perform lookups on the same prepared statement:
    public function fetchProductById($prodId)
    {
      if (!isset($this->products[$prodId])) {
          if (!$this->prodPreparedStmt) {
              $sql = 'SELECT * FROM products WHERE id = :id';
              $this->prodPreparedStmt = 
              $this->connection->pdo->prepare($sql);
          }
          $this->prodPreparedStmt->execute(['id' => $prodId]);
          $result = $this->prodPreparedStmt
          ->fetch(PDO::FETCH_ASSOC);
          $this->products[$prodId] = 
            Product::arrayToEntity($result, new Product());
      }
      return $this->products[$prodId];
    }
  6. We can now rework the fetchPurchasesForCustomer() method to have it embed an anonymous function that makes calls to both fetchPurchaseById() and fetchProductById(), and then assigns the resulting product entity to the newly found purchase entity. In this example, we do an initial lookup that just returns the IDs of all purchases for this customer. We then embed a sequence of anonymous functions in the Customer::$purchases property, storing the purchase ID as the array key, and the anonymous function as its value:
    public function fetchPurchasesForCustomer(Customer $cust)
    {
      $sql = 'SELECT id '
        . 'FROM purchases AS u '
        . 'WHERE u.customer_id = :id '
        . 'ORDER BY u.date';
      $stmt = $this->connection->pdo->prepare($sql);
      $stmt->execute(['id' => $cust->getId()]);
      while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $cust->addPurchaseLookup(
        $result['id'],
        function ($purchId, $service) { 
          $purchase = $service->fetchPurchaseById($purchId);
          $product  = $service->fetchProductById(
                      $purchase->getProductId());
          $purchase->setProduct($product);
          return $purchase; }
        );
      }
      return $cust;
    }

How it works...

Define the following classes based on the steps from this recipe as follows:

Class

Technique #1 steps

Application\Entity\Purchase

1 - 2, 7

Application\Entity\Product

3 - 4

Application\Entity\Customer

6, 16, + described in Chapter 5, Interacting with a Database.

Application\Database\CustomerOrmService_1

8 - 10

The second approach to this would be as follows:

Class

Technique #2 steps

Application\Entity\Customer

2

Application\Database\CustomerOrmService_2

3 - 6

In order to implement approach #1, where entities are embedded, define a calling program called chap_11_orm_embedded.php, which sets up autoloading and uses the appropriate classes:

<?php
define('DB_CONFIG_FILE', '/../config/db.config.php');
require __DIR__ . '/../Application/Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__ . '/..');
use Application\Database\Connection;
use Application\Database\CustomerOrmService_1;

Next, create an instance of the service, and look up a customer using a random ID:

$service = new CustomerOrmService_1(new Connection(include __DIR__ . DB_CONFIG_FILE));
$id   = rand(1,79);
$cust = $service->fetchByIdAndEmbedPurchases($id);

In the view logic, you will have acquired a fully populated Customer entity by way of the fetchByIdAndEmbedPurchases() method. Now all you need to do is to call the right getters to display information:

  <!-- Customer Info -->
  <h1><?= $cust->getname() ?></h1>
  <div class="row">
    <div class="left">Balance</div><div class="right">
      <?= $cust->getBalance(); ?></div>
  </div>
    <!-- etc. -->

The logic needed to display purchase information would then look something like the following HTML. Notice that Customer::getPurchases() returns an array of Purchase entities. To get product information from the Purchase entity, inside the loop, call Purchase::getProduct(), which produces a Product entity. You can then call any of the Product getters, in this example, Product::getTitle():

  <!-- Purchases Info -->
  <table>
  <?php foreach ($cust->getPurchases() as $purchase) : ?>
  <tr>
  <td><?= $purchase->getTransaction() ?></td>
  <td><?= $purchase->getDate() ?></td>
  <td><?= $purchase->getQuantity() ?></td>
  <td><?= $purchase->getSalePrice() ?></td>
  <td><?= $purchase->getProduct()->getTitle() ?></td>
  </tr>
  <?php endforeach; ?>
</table>

Turning your attention to the second approach, which uses secondary lookups, define a calling program called chap_11_orm_secondary_lookups.php, which sets up autoloading and uses the appropriate classes:

<?php
define('DB_CONFIG_FILE', '/../config/db.config.php');
require __DIR__ . '/../Application/Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__ . '/..');
use Application\Database\Connection;
use Application\Database\CustomerOrmService_2;

Next, create an instance of the service, and look up a customer using a random ID:

$service = new CustomerOrmService_2(new Connection(include __DIR__ . DB_CONFIG_FILE));
$id   = rand(1,79);

You can now retrieve an Application\Entity\Customer instance and call fetchPurchasesForCustomer() for this customer, which embeds the sequence of anonymous functions:

$cust = $service->fetchById($id);
$cust = $service->fetchPurchasesForCustomer($cust);

The view logic for displaying core customer information remains the same as described previously. The logic needed to display purchase information would then look something like the following HTML code snippet. Notice that Customer::getPurchases() returns an array of anonymous functions. Each function call returns one specific purchase and related products:

<table>
  <?php foreach($cust->getPurchases() as $purchId => $function) : ?>
  <tr>
  <?php $purchase = $function($purchId, $service); ?>
  <td><?= $purchase->getTransaction() ?></td>
  <td><?= $purchase->getDate() ?></td>
  <td><?= $purchase->getQuantity() ?></td>
  <td><?= $purchase->getSalePrice() ?></td>
  <td><?= $purchase->getProduct()->getTitle() ?></td>
  </tr>
  <?php endforeach; ?>
</table>

Here is an example of the output:

How it works...

Tip

Best practice

Although each iteration of the loop represents two independent database queries (one for purchase, one for product), efficiency is retained by the use of prepared statements. Two statements are prepared in advance: one that looks up a specific purchase, and one that looks up a specific product. These prepared statements are then executed multiple times. Also, each product retrieval is independently stored in an array, resulting in even greater efficiency.

See also

Probably the best example of a library that implements object-relational mapping is Doctrine. Doctrine uses an embedded approach that its documentation refers to as a proxy. For more information, please refer to http://www.doctrine-project.org/projects/orm.html.

You might also consider reviewing a training video on Learning Doctrine, available from O'Reilly Media at http://shop.oreilly.com/product/0636920041382.do. (Disclaimer: this is a shameless plug by the author of both this book and this video!)