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

Laravel

Laravel is one of the most popular PHP frameworks, and according to the Laravel official website, it is a framework for Web Artisans. Laravel is beautiful, powerful, and has tons of features that can enable developers to write efficient and quality code. The Laravel official documentation is well written and very easy to understand. So, let's play a little with Laravel.

Installation

Installation is very easy and simple. Let's use Composer to install Laravel. We discussed Composer in Appendix A. Issue the following command in the terminal to install and create a project in Laravel:

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

If Composer is not installed globally on the system, place composer.phar in a directory where Laravel should be installed and issue the following command in the terminal at the root of this directory:

php composer.phar create-project --prefer-dist laravel/laravel packt

Now, Laravel will be downloaded, and a new project with the name packt will be created. Also, Composer will download and install all the dependencies for the project.

Open the browser and head to the project's URL, and we will be welcomed with a nice simple page saying Laravel 5.

Note

As of the writing of this book, Laravel 5.2.29 is the latest version available. However, if Composer is used, then every time the composer update command is used, Laravel and all other components will be automatically updated.

Features

Laravel provides tons of features, and we will only discuss a few here.

Routing

Laravel provides powerful routing. Routes can be grouped, and prefixes, namespaces, and middleware can be defined for route groups. Also, Laravel supports all HTTP methods, including POST, GET, DELETE, PUT, OPTIONS, and PATCH. All the routes are defined in the routes.php file in the application's app folder. Take a look at the following example:

Route::group(['prefix' => 'customer', 'namespace' => 'Customer', 'middleware' => 'web'], function() {
    Route::get('/', 'CustomerController@index');
    Route::post('save', 'CustomerController@save');
    Route::delete('delete/{id}', 'CustomerController@delete');
});

In the preceding snippet, we created a new routes group. This will be only used when the URL has a prefixed customer. For example, if a URL is similar to domain.com/customer, this group will be used. We also used a customer namespace. Namespacing allows us to use standard PHP namespaces and divide our files in subfolders. In the preceding example, all customer controllers can be placed in the Customer subfolder in the Controllers directory, and the controller will be created as follows:

namespace App\Http\Controllers\Customer

use App\Http\{
Controllers\Controller,
Requests,
};
use Illuminate\Http\Request;

Class CustomerController extends Controller
{
  …
  …
}

So, namespacing a route group enables us to place our controller files in subfolders, which are easy to manage. Also, we used the web middleware. Middleware provides a way to filter the request before entering the application, which enables us to use it to check whether a user is logged in or not, the CSRF protection, or whether there are any other actions that can be performed in a middleware and need to be performed before the request is sent to application. Laravel comes with a few middleware, including web, api, auth, and so on.

If a route is defined as GET, no POST request can be sent to this route. It is very convenient, which enables us to not worry about the request method filtering. However, HTML forms do not support the HTTP methods like DELETE, PATCH, and PUT. For this, Laravel provides method spoofing, in which a hidden form field with name _method and the value of the HTTP method is used to make this request possible. For example, in our routes group, to make the request possible to delete a route, we need a form similar to the following:

<form action="/customer/delete" method="post">
  {{ method_field('DELETE') }}
  {{ csrf_field() }}
</form>

When the preceding form is submitted, it will work, and the delete route will be used. Also, we created a CSRF hidden field, which is used for CSRF protection.

Note

Laravel routing is very interesting, and it is a big topic. More in-depth detail can be found at https://laravel.com/docs/5.2/routing.

Eloquent ORM

Eloquent ORM provides active records to interact with the database. To use Eloquent ORM, we have to just extend our models from the Eloquent model. Let's have a look at a simple user model, as follows:

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
  //protected $table = 'customer';
  //protected $primaryKey = 'id_customer';
  …
  …
}

That's it; we have a model that can handle all the CRUD operations now. Note that we commented the $table property and did the same for $primaryKey. This is because Laravel uses a plural name of the class to look for the table unless the table is defined with the protected $table property. In our case, Laravel will look for table name users and use it. However, if we want to use a table named customers, we can just uncomment the line, as follows:

protected $table = 'customers';

Similarly, Laravel thinks that a table will have a primary key with the column name id. However, if another column is needed, we can override the default primary key, as follows:

protected $primaryKey = 'id_customer';

Eloquent models also make it easy for timestamps. By default, if the table has the created_at and updated_at fields, then these two dates will be generated automatically and saved. If no timestamps are required, these can be disabled, as follows:

protected $timestamps = false;

Saving data to the table is easy. The table columns are used as properties of the models, so if our customer table has columns such as name, email, phone, and so on, we can set them as follows in our customer controller, mentioned in the routing section:

namespace App\Http\Controllers\Customer

use App\Http\{
Controllers\Controller,
Requests,
};
use Illuminate\Http\Request;
use App\Customer

Class CustomerController extends Controller
{
  public function save(Request $request)
  {
    $customer = new Customer();
    $customer->name = $request->name;
    $customer->email = $request->email;
    $customer->phone = $request->phone;
    
    $customer->save();
    
  }
}

In the preceding example, we added the save action to our controller. Now, if a POST or GET request is made along the form data, Laravel assigns all the form-submitted data to a Request object as properties with the same names as that of the form fields. Then, using this request object, we can access all the data submitted by the form either using POST or GET. After assigning all the data to model properties (the same names as those of table columns), we can just call the save method. Now, our model does not have any save method, but its parent class, which is the Eloquent model, has this method defined. However, we can override this save method in our model class in case we need some other features in this method.

Fetching data from the Eloquent model is also easy. Let's try an example. Add a new action to the customer controller, as follows:

public function index()
{
  $customers = Customer::all();
}

We used the all() static method in the model, which is basically defined in the Eloquent model, which, in turn, fetches all the data in our customers table. Now, if we want to get a single customer by the primary key, we can use the find($id) method, as follows:

$customer = Customer::find(3);

This will fetch the customer with the ID 3.

Updating is simple, and the same save() method is used, as shown here:

$customer = Customer::find(3);
$customer->name = 'Altaf Hussain';

$customer->save();

This will update the customer with the ID 3. First, we loaded the customer, then we assigned new data to its properties, and then we called the same save() method. Deleting the model is simple and easy and can be done as follows:

$customer = Customer::find(3);
$customer->delete();

We first loaded the customer with the ID 3, and then we called the delete method, which will delete the customer with the ID 3.

Note

Laravel's Eloquent models are very powerful and provide lots of features. These are well explained in the documentation at https://laravel.com/docs/5.2/eloquent. The Laravel database section is also worth reading and can be found at https://laravel.com/docs/5.2/database.

Artisan CLI

Artisan is the command-line interface provided with Laravel, and it has some nice commands that can be used for quicker operations. It has lots of commands, and a full list can be seen using the following command:

php artisan list

This will list all the options and commands available.

Note

The php artisan command should be run in the same directory in which the artisan file is located. It is placed at the root of the project.

Some of the basic commands are as follows:

  • make:controller: This command creates a new controller in the Controllers folder. The command can be used as follows:
    php artisan make:controller MyController
    

    If a namespaced controller is required, as it happened before with the Customer namespace, it can be done as follows:

    php artisan make:controller Customer/CustomerController
    

    This command will create CustomerController in the Customer folder. If the Customer folder is not available, it will create the folder as well.

  • make:model: This creates a new model in the app folder. The syntax is the same as the make:controller command, as follows:
    php artisan make:model Customer
    

    For the namespaced models, it can be used as follows:

    php artisan make:model Customer/Customer
    

    This will create the Customer model in the Customer folder and use the Customer namespace for it.

  • make:event: This creates a new event class in the Events folder. It can be used as follows:
    php artisan make:event MyEvent
    
  • make:listener: This command creates a new listener for an event. This can be used as follows:
    php artisan make:listener MyListener --event MyEvent
    

    The preceding command will create a new listener for our MyEvent event. We have to always mention the event for which we need to create a listener using the --event option.

  • make:migration: This command creates a new migration in the database/migrations folder.
  • php artisan migrate: This runs all the available migrations that are not executed.
  • php artisan optimize: This command optimizes the framework for better performance.
  • php artisan down: This puts the application in maintenance mode.
  • php artisan up: This command brings the application back live from the maintenance mode.
  • php artisan cache:clear: This command clears the application cache.
  • php artisan db:seed: This command seeds the database with records.
  • php artisan view:clear: This clears all the compiled view files.

    Note

    More detail about the Artisan console or Artisan CLI can be found in the documentation at https://laravel.com/docs/5.2/homestead.

Migrations

Migrations is another powerful feature in Laravel. In migrations, we define the database schemas—whether it creates tables, removes tables, or adds/updates columns in the tables. Migrations are very convenient in deployment and act as version control for the database. Let's create a migration for our customer table that is not available in the database yet. To create a migration, issue the following command in the terminal:

php artisan make:migration create_custmer_table

A new file in the database/migrations folder will be created with the filename create_customer_table prefixed with the current date and a unique ID. The class is created as CreateCustomerTable. This is a class as follows:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCustomerTable extends Migrations
{
  //Run the migrations
  
  public function up()
  {
    //schemas defined here
  }

  public function down()
  {
    //Reverse migrations
  }
}

The class will have two public methods: up() and down(). The up() method should have all the new schemas for the table(s). The down() method is responsible for reversing the executed migration. Now, lets add the customers table schema to the up() method, as follows:

public function up()
{
  Schema::create('customers', function (Blueprint $table)
  {
    $table->increments('id', 11);
    $table->string('name', 250)
    $table->string('email', 50);
    $table->string('phone', 20);
    $table->timestamps();
  });
}
public function down()
{
  Schema::drop('customers');
}

In the up() method, we defined the schema and table name. Columns for the table are individually defined, including the column size. The increments() method defines the autoincrement column, which, in our case, is the id column. Next, we created three string columns for name, email, and phone. Then, we used the timestamps() method, which creates the created_at and updated_at timestamp columns. In the down() method, we just used the drop() method of the Schema class to drop out the customers table. Now, we need to run our migrations using the following command:

php artisan migrate

The preceding command will not only run our migration but will also run all those migrations that are not executed yet. When a migration is executed, Laravel stores the migration name in a table called migrations, from where Laravel decides which migrations it has to execute and which to skip.

Now, if we need to roll back the latest executed migration, we can use the following command:

php artisan migrate:rollback

This will roll back to the last batch of migrations. To roll back all the migrations of the application, we can use the reset command, as follows:

php artisan migrate:reset

This will roll back the complete application migrations.

Migrations make it easy for deployment because we won't need to upload the database schemas every time we create some new changes in the tables or database. We will just create the migrations and upload all the files, and after this, we will just execute the migration command, and all the schemas will be updated.

Blade templates

Laravel comes with its own template language called Blade. Also, Blade template files support plain PHP code. Blade template files are compiled to plain PHP files and are cached until they are changed. Blade also supports layouts. For example, the following is our master page layout in Blade, placed in the resources/views/layout folder with the name master.blade.php. Take a look at the following code:

<!DOCTYPE html>
<html>
  <head>
    <title>@yield('title')</title>
  </head>
  <body>
    @section('sidebar')
      Our main sidebar
      @show

      <div class="contents">
        @yield('content')
      </div>
  </body>
</html>

In the preceding example, we had a section for the sidebar that defines a content section. Also, we had @yield, which displays the contents of a section. Now, if we want to use this layout, we will need to extend it in the child template files. Let's create the customers.blade.php file in the resources/views/ folder and place the following code in it:

@extend('layouts.master')
  @section('title', 'All Customers')
  @section('sidebar')
  This will be our side bar contents
  @endsection
  @section('contents')
    These will be our main contents of the page
  @endsection

As can be seen in the preceding code, we extended the master layout and then placed contents in every section of the master layout. Also, it is possible to include different templates in another template. For example, let's have two files, sidebar.blade.php and menu.blade.php, in the resources/views/includes folder. Then, we can include these files in any template, as follows:

@include(includes.menu)
@include(includes.sidebar)

We used @include to include a template. The dot (.) indicates a folder separation. We can easily send data to Blade templates or views from our controllers or routers. We have to just pass the data as an array to a view, as follows:

return view('customers', ['count => 5]);

Now, count is available in our customers view file and can be accessed as follows:

Total Number of Customers: {{ count }}

Yes, Blade uses double curly braces to echo a variable. For control structures and loops, let's have another example. Let's send data to the customers view, as follows:

return view('customers', ['customers' => $allCustomers]);

Now, our customers view file will be similar to the following if we want to display all the customers data:

…
…
@if (count($customers) > 0)
{{ count($customers) }} found. <br />
@foreach ($customers as $customer)
{{ $customer->name }} {{ $customer->email }} {{ $customer->phone }} <br>
@endforeach
  
@else
Now customers found.
@endif;
…
…

All the preceding syntax looks familiar as it is almost the same as plain PHP. However, to display a variable, we have to use double curly braces {{}}.

Note

A nice and easy-to-read documentation for Blade templates can be found at https://laravel.com/docs/5.2/blade.

Other features

We only discussed a few basic features in the previous section. Laravel has tons of other features, such as Authentication and Authorization, which provide an easy way to authenticate and authorize users. Also, Laravel provides a powerful caching system, which supports file-based cache, the Memcached, and Redis cache. Laravel also provides events and listeners for these events, which is very convenient when we want to perform a specific action and when a specific event occurs. Laravel supports localization, which enables us to use localized contents and multiple languages. Laravel also supports task scheduling and queues, in which we schedule some tasks to run at a specific time and queue some tasks to be run when their turn arrives.