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 SOAP server

As with the SOAP client, we can use the PHP SOAP extension to implement a SOAP server. The most difficult part of the implementation will be generating the WSDL from the API class. We do not cover that process here as there are a number of good WSDL generators available.

How to do it...

  1. First, you need an API that will be handled by the SOAP server. For this example, we define an Application\Web\Soap\ProspectsApi class that allows us to create, read, update, and delete the prospects table:
    namespace Application\Web\Soap;
    use PDO;
    class ProspectsApi
    {
      protected $registerKeys;
      protected $pdo;
            
      public function __construct($pdo, $registeredKeys)
      {
        $this->pdo = $pdo;
        $this->registeredKeys = $registeredKeys;
      }
    }
  2. We then define methods that correspond to create, read, update, and delete. In this example, the methods are named put(), get(), post(), and delete(). These, in turn, call methods that generate SQL requests that are executed from a PDO instance. An example for get() is as follows:
    public function get(array $request, array $response)
    {
      if (!$this->authenticate($request)) return FALSE;
      $result = array();
      $id = $request[self::ID_FIELD] ?? 0;
      $email = $request[self::EMAIL_FIELD] ?? 0;
      if ($id > 0) {
          $result = $this->fetchById($id);  
          $response[self::ID_FIELD] = $id;
      } elseif ($email) {
          $result = $this->fetchByEmail($email);
          $response[self::ID_FIELD] = $result[self::ID_FIELD] ?? 0;
      } else {
          $limit = $request[self::LIMIT_FIELD] 
            ?? self::DEFAULT_LIMIT;
          $offset = $request[self::OFFSET_FIELD] 
            ?? self::DEFAULT_OFFSET;
          $result = [];
          foreach ($this->fetchAll($limit, $offset) as $row) {
            $result[] = $row;
          }
      }
      $response = $this->processResponse(
        $result, $response, self::SUCCESS, self::ERROR);
        return $response;
      }
    
      protected function processResponse($result, $response, 
                                         $success_code, $error_code)
      {
        if ($result) {
            $response['data'] = $result;
            $response['code'] = $success_code;
            $response['status'] = self::STATUS_200;
        } else {
            $response['data'] = FALSE;
            $response['code'] = self::ERROR_NOT_FOUND;
            $response['status'] = self::STATUS_500;
        }
        return $response;
      }
  3. You can then generate a WSDL from your API. There are quite a few PHP-based WSDL generators available (see the There's more... section). Most require that you add phpDocumentor tags before the methods that will be published. In our example, the two arguments are both arrays. Here is the full WSDL for the API discussed earlier:
    <?xml version="1.0" encoding="UTF-8"?>
      <wsdl:definitions xmlns:tns="php7cookbook" targetNamespace="php7cookbook" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
      <wsdl:message name="getSoapIn">
        <wsdl:part name="request" type="tns:array" />
        <wsdl:part name="response" type="tns:array" />
      </wsdl:message>
      <wsdl:message name="getSoapOut">
        <wsdl:part name="return" type="tns:array" />
      </wsdl:message>
      <!—some nodes removed to conserve space -->
      <wsdl:portType name="CustomerApiSoap">
      <!—some nodes removed to conserve space -->
      <wsdl:binding name="CustomerApiSoap" type="tns:CustomerApiSoap">
      <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc" />
        <wsdl:operation name="get">
          <soap:operation soapAction="php7cookbook#get" />
            <wsdl:input>
              <soap:body use="encoded" encodingStyle= "http://schemas.xmlsoap.org/soap/encoding/" namespace="php7cookbook" parts="request response" />
            </wsdl:input>
            <wsdl:output>
              <soap:body use="encoded" encodingStyle= "http://schemas.xmlsoap.org/soap/encoding/" namespace="php7cookbook" parts="return" />
            </wsdl:output>
        </wsdl:operation>
      <!—some nodes removed to conserve space -->
      </wsdl:binding>
      <wsdl:service name="CustomerApi">
        <wsdl:port name="CustomerApiSoap" binding="tns:CustomerApiSoap">
        <soap:address location="http://localhost:8080/" />
        </wsdl:port>
      </wsdl:service>
      </wsdl:definitions>
  4. Next, create a chap_07_simple_soap_server.php file, which will execute the SOAP server. Start by defining the location of the WSDL and any other necessary files (in this case, one for database configuration). If the wsdl parameter is set, deliver the WSDL rather than attempting to process the request. In this example, we use a simple API key to authenticate requests. We then create a SOAP server instance, assign an instance of our API class, and run handle():
    <?php
    define('DB_CONFIG_FILE', '/../config/db.config.php');
    define('WSDL_FILENAME', __DIR__ . '/chap_07_wsdl.xml');
          
    if (isset($_GET['wsdl'])) {
        readfile(WSDL_FILENAME);
        exit;
    }
    $apiKey = include __DIR__ . '/api_key.php';
    require __DIR__ . '/../Application/Web/Soap/ProspectsApi.php';
    require __DIR__ . '/../Application/Database/Connection.php';
    use Application\Database\Connection;
    use Application\Web\Soap\ProspectsApi;
    $connection = new Application\Database\Connection(
      include __DIR__ . DB_CONFIG_FILE);
    $api = new Application\Web\Soap\ProspectsApi(
      $connection->pdo, [$apiKey]);
    $server = new SoapServer(WSDL_FILENAME);
    $server->setObject($api);
    echo $server->handle();

    Note

    Depending on the settings for your php.ini file, you may need to disable the WSDL cache, as follows:

    ini_set('soap.wsdl_cache_enabled', 0);

    If you have problems with incoming POST data, you can adjust this parameter as follows:

    ini_set('always_populate_raw_post_data', -1);

How it works...

You can easily test this recipe by first creating your target API class, and then generating a WSDL. You can then use the built-in PHP webserver to deliver the SOAP service with this command:

php -S localhost:8080 chap_07_simple_soap_server.php 

You can then use the SOAP client discussed in the previous recipe to make a call to test the SOAP service:

<?php
define('WSDL_URL', 'http://localhost:8080?wsdl=1');
$clientKey = include __DIR__ . '/api_key.php';
try {
  $client = new SoapClient(WSDL_URL);
  $response = [];
  $email = some_email_generated_by_test;
  $email = 'test5393@unlikelysource.com';
  echo "\nGet Prospect Info for Email: " . $email . "\n";
  $request = ['token' => $clientKey, 'email' => $email];
  $result = $client->get($request,$response);
  var_dump($result);
  
} catch (SoapFault $e) {
  echo 'ERROR' . PHP_EOL;
  echo $e->getMessage() . PHP_EOL;
} catch (Throwable $e) {
  echo 'ERROR' . PHP_EOL;
  echo $e->getMessage() . PHP_EOL;
} finally {
  echo $client->__getLastResponse() . PHP_EOL;
}

Here is the output for email address test5393@unlikelysource.com:

How it works...

See also

A simple Google search for WSDL generators for PHP came back with easily a dozen results. The one used to generate the WSDL for the ProspectsApi class was based on https://code.google.com/archive/p/php-wsdl-creator/. For more information on phpDocumentor, refer to the page at https://www.phpdoc.org/.