<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title>Most Recent Articles</title><link>http://channel.example.org</link><description>Most recent articles</description><atom:link href="https://www.startutorial.com/articles/all.rss" rel="self" type="application/rss+xml"/><item><title>Monitoring a PHP application</title><link>https://www.startutorial.com/articles/view/monitoring-a-php-application</link><guid>https://www.startutorial.com/articles/view/monitoring-a-php-application<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;After months and months of development, our PHP application is finally live and running. What is going to happen next?&lt;/p&gt;&#13;
&#13;
&lt;p&gt;In an imaginary world, we sit and relax. We watch our application get popular and users flood in. And the application will just handle itself nicely because we have done all the testing. Right? Unfortunately, that is not the truth. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;As users come in, errors start happening. No matter how many tests we have done. It is impossible to cover all the edge cases caused by real users. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;Monitoring is the next step after development. It is the next thing we need to do after our application goes live. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;In this tutorial, we discuss what things to monitor and their related services we have used. &lt;/p&gt;&#13;
&#13;
&lt;h2 id="toc_1"&gt;Request monitoring&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;For each web request, we want to monitor its metrics such as its URI, request method, response time, status code, and so on. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;From the metrics above, we can derive average response time, error rates, and so on. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;Related services: &lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Datadog: https://www.datadoghq.com/&lt;/li&gt;&#13;
&lt;li&gt;Amazon CloudWatch: https://aws.amazon.com/cloudwatch/ &lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;h2 id="toc_2"&gt;Exception monitoring&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;Exceptions from our codebase typically indicate some critical errors or edge cases in our system.  We want to fix them before users get affected by their occurrence.  &lt;/p&gt;&#13;
&#13;
&lt;p&gt;Related services: &lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Raygun: https://raygun.com/languages/php&lt;/li&gt;&#13;
&lt;li&gt;Rollbar: https://rollbar.com/error-tracking/php/&lt;/li&gt;&#13;
&lt;li&gt;Bugsnag: https://www.bugsnag.com/platforms/php&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;h2 id="toc_3"&gt;Log monitoring&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;When it comes to debugging and troubleshooting. Logs are essential. They contain information we need to fix errors and trace user behaviors. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;Related service:&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Loggly: https://www.loggly.com/&lt;/li&gt;&#13;
&lt;li&gt;Papertrailapp: https://papertrailapp.com/&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;h2 id="toc_4"&gt;Dependencies monitoring&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;Modern PHP applications use external services(dependencies) such as MySQL, Elasticsearch, Redis, and so on. We need to monitor their performance to ensure the whole application&amp;#39;s health. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;Related tool:&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Solarwinds: https://www.solarwinds.com/server-application-monitor/use-cases/mysql-monitor&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;h2 id="toc_5"&gt;End&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;What other information do you monitor and what tools do you use? Please leave a comment to let us know. &lt;/p&gt;&#13;
&#13;
</description><pubDate>Thu, 28 May 2020 06:41:21 +0000</pubDate></item><item><title>Server testing using curl</title><link>https://www.startutorial.com/articles/view/server-testing-using-curl</link><guid>https://www.startutorial.com/articles/view/server-testing-using-curl<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;Project curl is a command-line tool that is used to do Internet transfers for resources specified as URLs using Internet protocols. You can read more about its history at https://ec.haxx.se/. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;In this tutorial, we learn about using curl to do some simple server testing. &lt;/p&gt;&#13;
&#13;
&lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&lt;ol class="well"&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_0"&gt;Examine response header&lt;/a&gt;                             &#13;
&lt;/li&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_1"&gt;Show response time&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_2"&gt;Send request header&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_3"&gt;The End&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;/ol&gt;&#13;
&#13;
&lt;h2 id="toc_0"&gt;Examine response header&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;To verify if a proxy server cache is working,  we can check the response&amp;#39;s header &amp;quot;x-proxy-cache&amp;quot; value. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;Examine response header using curl: &lt;/p&gt;&#13;
&#13;
&lt;p&gt;&lt;code&gt;curl  -I https://yoursite.com&lt;/code&gt;&lt;/p&gt;&#13;
&#13;
&lt;p&gt;Output:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;HTTP/2 200 &#13;
server: nginx/1.14.0&#13;
date: Sat, 03 Aug 2019 05:44:27 GMT&#13;
content-type: text/html; charset=UTF-8&#13;
expires: Thu, 8 Aug 2019 05:44:27 GMT&#13;
cache-control: public, max-age=432000&#13;
last-modified: Sat, 3 Aug 2019 05:43:27 GMT&#13;
x-ua-compatible: IE=Edge&#13;
x-proxy-cache: MISS&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h2 id="toc_1"&gt;Show response time&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;Response time is a simple yet straightforward metric to benchmark when optimizing our site. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;To check response time using curl: &lt;/p&gt;&#13;
&#13;
&lt;p&gt;&lt;code&gt;curl  -s -w &amp;quot;%{time_total}\n&amp;quot; -o null https://yoursite.com&lt;/code&gt;&lt;/p&gt;&#13;
&#13;
&lt;p&gt;Options:&#13;
+ -s: run it in silent mode. Do not show progress info.&#13;
+ -w: format the output string using a placeholder.&#13;
+ -o: write the output to a file. Here we discard it by writing to null. &lt;/p&gt;&#13;
&#13;
&lt;h2 id="toc_2"&gt;Send request header&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;When we need to send &amp;quot;no-cache&amp;quot; request to the header to test the proxy cache server. We can do so via curl too.&lt;/p&gt;&#13;
&#13;
&lt;p&gt;Send request header using curl:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;curl -H &amp;#39;Cache-Control: no-cache&amp;#39; -I https://yoursite.com&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;Output:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;HTTP/2 200 &#13;
server: nginx/1.14.0&#13;
date: Sat, 03 Aug 2019 06:27:49 GMT&#13;
content-type: text/html; charset=UTF-8&#13;
expires: Thu, 8 Aug 2019 06:27:49 GMT&#13;
cache-control: public, max-age=432000&#13;
last-modified: Sat, 3 Aug 2019 06:26:49 GMT&#13;
x-ua-compatible: IE=Edge&#13;
x-proxy-cache: BYPASS&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h2 id="toc_3"&gt;End&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;We hope this simple tutorial helped you with your development.&lt;/p&gt;&#13;
</description><pubDate>Thu, 28 May 2020 06:39:07 +0000</pubDate></item><item><title>The 3 rules of thumb to make your PHP application horizontal scale ready</title><link>https://www.startutorial.com/articles/view/the-3-rules-of-thumb-to-make-your-php-application-horizontal-scale-ready</link><guid>https://www.startutorial.com/articles/view/the-3-rules-of-thumb-to-make-your-php-application-horizontal-scale-ready<isPermaLink>true</isPermaLink></guid><description>&#13;
&lt;p&gt;In simple terms, to horizontally scale a PHP application means adding more servers instead of upgrading the existing servers. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;However, to technically achieve that, your PHP application must be ready for the scale. In this article, we share 3 rules of thumb to make your PHP application ready for a horizontal scale. &lt;/p&gt;&#13;
&#13;
&#13;
&#13;
&#13;
&lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
&lt;ol class="well"&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_1"&gt;Remote database connection&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_2"&gt;Centralised file storage&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_3"&gt;Centralized session storage&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_4"&gt;The end&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&#13;
&lt;/ol&gt;&#13;
&#13;
&#13;
&lt;h6 id="toc_1"&gt;Remote database connection&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;When the database server is sitting independently, we do not have to worry about breaking our database while upgrading our web servers.  Hence our PHP application must allow remote database connection. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;It is recommended to use  PDO when working with a database in PHP. And PDO supports remote database connection out of the box. &lt;/p&gt;&#13;
&#13;
&lt;h6 id="toc_2"&gt;Centralised file storage&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;File uploads are commonly stored in a web server, however, this can cause a major issue when scaling web servers horizontally, since common approaching is to remove the old server and migrate to a new server. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;So files must be stored in a centralized location.  There are cloud storage services such as Amazon S3, Azure Storage, and Google Storage.  All of them are a good fit for centralized file storage. &lt;/p&gt;&#13;
&#13;
&lt;h6 id="toc_3"&gt;Centralized session storage&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;Almost every PHP application involves user authentication and most of the authentication in PHP is using session storge. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;In PHP, We use the file as session storage by default. It is out of the box and it is super handy to pick up, we almost have to do nothing. However, it comes with a huge trade-off. When you migrate a web server to a new one, you lose all your users&amp;#39; sessions instantly. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;To scale PHP application horizontally in peace, your session storage must be centralized.  Cloud services such as Amazon DynmoDB and Amazon ElastiCache can be used as centralized session storage. &lt;/p&gt;&#13;
&#13;
&lt;h6 id="toc_4"&gt;The end&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;We hope you find this article tutorial and make your PHP application horizontal scale ready!&lt;/p&gt;&#13;
</description><pubDate>Sun, 26 Apr 2020 08:13:45 +0000</pubDate></item><item><title>Types of caching in a PHP web application</title><link>https://www.startutorial.com/articles/view/types-of-caching-in-a-php-web-application</link><guid>https://www.startutorial.com/articles/view/types-of-caching-in-a-php-web-application<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;As a web developer, you must have heard the term &amp;quot;cache&amp;quot; in various situations. To help you fully understand what cache means, we wrote this article. &lt;/p&gt;&#13;
&#13;
&#13;
&lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
&lt;ol class="well"&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_1"&gt;OpCode Cache&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_2"&gt;Application Cache&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_3"&gt;HTTP Cache&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_4"&gt;Proxy Cache&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_5"&gt;End&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;/ol&gt;&#13;
&#13;
&#13;
&lt;h6 id="toc_1"&gt;OpCode Cache&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;When running a PHP script. The interpreter will parse the script into a series of operation codes, commonly known as &amp;quot;opcodes&amp;quot;. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;By caching the opcode in memory, we can gain significant performance improvement. This is known as opCode cache. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;There is a list of well-know opCode cache engines and they are:&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Zend OpCache&lt;/li&gt;&#13;
&lt;li&gt;APC User Cache&lt;/li&gt;&#13;
&lt;li&gt;Alternative PHP Cache&lt;/li&gt;&#13;
&lt;li&gt;Xcache&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;p&gt;By default, PHP ships with Zend OpCache. &lt;/p&gt;&#13;
&#13;
&lt;h6 id="toc_2"&gt;Application Cache&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;When building an application, we can utilize some cache strategies to avoid slow response:  &lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Store data that is not changed often in a cache. &lt;/li&gt;&#13;
&lt;li&gt;Store time-consuming computed data in a cache.&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;p&gt;Above are known as application cache. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;When implementing the application cache, we have a lot of options in where to store the cache values. Following solutions are typically used to store the cache values:&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Redis&lt;/li&gt;&#13;
&lt;li&gt;Memcached&lt;/li&gt;&#13;
&lt;li&gt;Database&lt;/li&gt;&#13;
&lt;li&gt;File system&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;h6 id="toc_3"&gt;HTTP Cache&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;Most of our PHP applications are built for the web and accessed by a browser. The browser interacts with our application via HTTP protocol. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;By utilizing the HTTP cache headers, a browser stores the response locally in its cache, this saves it from requesting the same data again via the network. This is known as HTTP cache. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;Commonly used HTTP Cache headers are:&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Cache-control&lt;/li&gt;&#13;
&lt;li&gt;Pragma&lt;/li&gt;&#13;
&lt;li&gt;Expires&lt;/li&gt;&#13;
&lt;li&gt;Etag&lt;/li&gt;&#13;
&lt;li&gt;Last-Modified&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;h6 id="toc_4"&gt;Proxy Cache&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;OpCode cache, application cache, and HTTP cache are great to help with application speed improvement. However, all the requests still go through the webserver. When the concurrency of the application is high, the web server may have a difficult time handling the requests. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;By placing a proxy server in front of the webserver, we can not only significantly reduce the web server&amp;#39;s load, but also we can improve the speed greatly because proxy server stores the cached response inside its memory.  &lt;/p&gt;&#13;
&#13;
&lt;p&gt;The strategy above is known as a proxy cache. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;Well-known proxy cache servers are:&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Nginx&lt;/li&gt;&#13;
&lt;li&gt;Squid&lt;/li&gt;&#13;
&lt;li&gt;Varnish&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;h6 id="toc_5"&gt;End&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;We hope you have understood different cache means through this article. &lt;/p&gt;&#13;
</description><pubDate>Sun, 26 Apr 2020 08:08:46 +0000</pubDate></item><item><title>Setup CakePHP 3 in a subdirectory using Nginx</title><link>https://www.startutorial.com/articles/view/setup-cakephp-3-in-a-subdirectory-using-nginx</link><guid>https://www.startutorial.com/articles/view/setup-cakephp-3-in-a-subdirectory-using-nginx<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;When placing a CakePHP 3 project to a subdirectory, it will not work out of the box. Some specific Nginx setups are required for it to work. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;For demonstration purposes, suppose we want to place a CakePHP 3 project to a subdirectory called &lt;strong&gt;demo&lt;/strong&gt;. &lt;/p&gt;&#13;
&#13;
&lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&lt;ol class="well"&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_1"&gt;Serving static files&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_2"&gt;Serving PHP content&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_3"&gt;The End&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;/ol&gt;&#13;
&#13;
&lt;h6 id="toc_1"&gt;Serving static files&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;Static files are served directly from the webroot folder, so the Nginx configuration blocks looks like something below:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;location ~* /demo/(.*)\.(css|js|ico|gif|png|jpg|jpeg|ttf|woff)$ {&#13;
    root /var/www/your-website.com/public/demo/webroot/;&#13;
    try_files /$1.$2 =404;&#13;
}&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_2"&gt;Serving PHP content&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;Other requests will be directed to &lt;strong&gt;index.php&lt;/strong&gt; file which leads to the CakePHP&amp;#39;s router:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;location /demo {&#13;
    root /var/www/your-website.com/public/demo/webroot;&#13;
      try_files $uri $uri/ /demo/webroot/index.php$is_args$args;&#13;
}&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_3"&gt;The End&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;In this tutorial, we demonstrate how to set up a CakePHP 3 in a subdirectory using Nginx. Hope you find this technique useful. &lt;/p&gt;&#13;
</description><pubDate>Fri, 03 Apr 2020 02:59:34 +0000</pubDate></item><item><title>Redis caching engine for CakePHP 3</title><link>https://www.startutorial.com/articles/view/redis-caching-engine-for-cakephp-3</link><guid>https://www.startutorial.com/articles/view/redis-caching-engine-for-cakephp-3<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;CakePHP provides various options as an application&amp;#39;s caching engine out of the box. CakePHP&amp;#39;s documentation is detailed and provides most of the answers we need. But it lacks the information of setting up Redis server itself in a server. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;In this tutorial, we will show you how to setup Redis server in a ubuntu 16.04 machine. &lt;/p&gt;&#13;
&#13;
&lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&lt;ol class="well"&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_1"&gt;Update APT package list&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_2"&gt;Install Redis&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_3"&gt;Install PHP Redis extension&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_4"&gt;Connect CakePHP to Redis&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_5"&gt;The End&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;/ol&gt;&#13;
&#13;
&lt;h6 id="toc_1"&gt;Update APT package list&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;Update the APT package list by running:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;sudo apt-get update&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_2"&gt;Install Redis&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;Install Redis server on Ubuntu:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;sudo apt-get install redis-server&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_3"&gt;Install PHP Redis extension&lt;/h6&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;sudo apt-get install php-redis&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_4"&gt;Connect CakePHP to Redis&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;Now we have Redis running and the PHP extension is ready. We can connect our CakePHP application to the Redis server by providing the configuration setting at https://book.cakephp.org/3.0/en/core-libraries/caching.html#redisengine-options. &lt;/p&gt;&#13;
&#13;
&lt;h6 id="toc_5"&gt;End&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;Redis is an in-memory cache engine, so it is blazing fast. Hope you find this tutorial helpful. &lt;/p&gt;&#13;
&#13;
</description><pubDate>Fri, 03 Apr 2020 02:56:25 +0000</pubDate></item><item><title>Benefits of using value objects</title><link>https://www.startutorial.com/articles/view/benefits-of-using-value-objects</link><guid>https://www.startutorial.com/articles/view/benefits-of-using-value-objects<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;The value object is a term crafted from Domain-Driven Design book. According to Wikipedia, a value object is a small object that represents a simple entity whose equality is not based on identity.  &lt;/p&gt;&#13;
&#13;
&lt;p&gt;Money is a combination of a number and a currency. A period is a combination of a start time and end time.  Both concepts are perfect candidates for value objects. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;In this article, we share some benefits of using value objects. &lt;/p&gt;&#13;
&#13;
&lt;h2 id="toc_1"&gt;Built-in validation&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;A value object is always valid since its existence. Which means, to guard its validity, we have to handle the validation from its constructor. &lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;class Money&#13;
{&#13;
    private $number;&#13;
    private $currency;&#13;
&#13;
    public function __construct($number, $currency)&#13;
    {&#13;
        if ($number &amp;lt; 0) {&#13;
            throw new LogicException(&amp;#39;Invalid number for a money&amp;#39;);&#13;
        }&#13;
&#13;
        if (in_array($currency, $this-&amp;gt;getCurrencyCode())) {&#13;
            throw new LogicException(&amp;#39;Invalid currency for a money&amp;#39;);&#13;
        }&#13;
&#13;
        $this-&amp;gt;number = $number;&#13;
        $this-&amp;gt;currency = $currency;&#13;
    }&#13;
&#13;
}&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h2 id="toc_2"&gt;Safe usage&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;A value object is immutable, which means alter its attribute, it will return a brand new copy of itself. We never have to worry about changing a value object by reference.&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;class Money&#13;
{&#13;
    ... ...&#13;
&#13;
    public function topUp(Money $money)&#13;
    {&#13;
        if ($money-&amp;gt;getCurrency() != $this-&amp;gt;getCurrency()) {&#13;
            throw new LogicException(&amp;#39;Invalid topUp operation&amp;#39;);&#13;
        }&#13;
&#13;
        $newNumber = $money-&amp;gt;getNumber() + $this-&amp;gt;getNumber();&#13;
&#13;
        return new Money($newNumber, $this-&amp;gt;getCurrency());&#13;
    }&#13;
&#13;
}&#13;
&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h2 id="toc_3"&gt;The end&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;The concept of value objects is very helpful. It can improve our object-oriented design a lot, so we can write easy-to-maintain codebase. &lt;/p&gt;&#13;
</description><pubDate>Mon, 02 Mar 2020 07:33:31 +0000</pubDate></item><item><title>Benefits of using application service classes</title><link>https://www.startutorial.com/articles/view/benefits-of-using-application-service-classes</link><guid>https://www.startutorial.com/articles/view/benefits-of-using-application-service-classes<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;In today&amp;#39;s tutorial, we share an architect pattern called service class. &lt;/p&gt;&#13;
&#13;
&lt;h2 id="toc_1"&gt;Definition of a service class&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;Writing clean and reusable code is not easy, we learn different patterns to achieve that. The MVC(Model-view-controller) pattern is probably the first architect pattern you got to know. &lt;/p&gt;&#13;
&#13;
&lt;h3 id="toc_2"&gt;Stage 1: fat controller&lt;/h3&gt;&#13;
&#13;
&lt;p&gt;It is very convenient to write all the business logic inside the controller, that seems like the natural choice when we first using MVC. At this stage, our controllers are very big and it consists of most of our domain business. &lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;class OrdersController {&#13;
&#13;
    function purchase($ticketId)&#13;
    {&#13;
        $ticket = Ticket::find($ticketId);&#13;
&#13;
        if ($ticket-&amp;gt;get(&amp;#39;inventory&amp;#39;) &amp;lt; 0 ) {&#13;
            throw new LogicException(&amp;#39;ticket is sold out&amp;#39;);&#13;
        }&#13;
&#13;
        $userId = $this-&amp;gt;Auth-&amp;gt;user(&amp;#39;id&amp;#39;);&#13;
&#13;
        $order = Order::save([&#13;
            &amp;#39;user_id&amp;#39;=&amp;gt;$userId ,&#13;
            &amp;#39;ticket_id&amp;#39;=&amp;gt;$ticketId&#13;
        ]);&#13;
&#13;
        $this-&amp;gt;redirect($order-&amp;gt;get(&amp;#39;id&amp;#39;));&#13;
    }&#13;
}&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h3 id="toc_3"&gt;Stage 2: fat model&lt;/h3&gt;&#13;
&#13;
&lt;p&gt;At this stage,  we learn about TDD (test-driven development), it is absolutely the way to go. TDD does not only help us think before coding but also improves the overall project quality because we can now do refactoring! &lt;/p&gt;&#13;
&#13;
&lt;p&gt;However, it is pain in the ass to write unit tests for controllers. Because controller tests are basic end-to-end tests, we need to prepare data seeds, send HTTP requests and assert against the database results. These unit tests are time-consuming to write and slow to run.  &lt;/p&gt;&#13;
&#13;
&lt;p&gt;Therefore, we move our business logic to model and start writing fat models. &lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;class OrdersController {&#13;
&#13;
    function purchase($ticketId)&#13;
    {&#13;
        $userId = $this-&amp;gt;Auth-&amp;gt;user(&amp;#39;id&amp;#39;);&#13;
        &#13;
        $order = OrderModel::purchase($userId, $ticketId);&#13;
        &#13;
        $this-&amp;gt;redirect($order-&amp;gt;get(&amp;#39;id&amp;#39;));&#13;
    }&#13;
}&#13;
&#13;
class OrderModel&#13;
{&#13;
    public function purchase($userId, $ticketId)&#13;
    {&#13;
        $ticket = Ticket::find($ticketId);&#13;
&#13;
        if ($ticket-&amp;gt;get(&amp;#39;inventory&amp;#39;) &amp;lt; 0 ) {&#13;
            throw new LogicException(&amp;#39;ticket is sold out&amp;#39;);&#13;
        }&#13;
&#13;
        return Order::save([&#13;
            &amp;#39;user_id&amp;#39;=&amp;gt;$userId ,&#13;
            &amp;#39;ticket_id&amp;#39;=&amp;gt;$ticketId&#13;
        ]);&#13;
    }&#13;
}&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h3 id="toc_4"&gt;Stage 3: service class&lt;/h3&gt;&#13;
&#13;
&lt;p&gt;When the business logic only involves one model, it is easy to decide where to place the code. When it involves multiple models, the struggle begins. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;For instance, a user purchases a ticket. Shall we place the fat logic inside the user model, the ticket model or the order model? Whenever this happens, we tend to struggle with the best solution. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;This is when a service class comes to the play. Service class fits best to how we model the process:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class OrdersController {&#13;
&#13;
    function purchase($ticketId)&#13;
    {&#13;
        $userId = $this-&amp;gt;Auth-&amp;gt;user(&amp;#39;id&amp;#39;);&#13;
        &#13;
        $order = UserPurchaseService::purchase($userId, $ticketId);&#13;
        &#13;
        $this-&amp;gt;redirect($order-&amp;gt;get(&amp;#39;id&amp;#39;));&#13;
    }&#13;
}&#13;
&#13;
&#13;
class UserPurchaseService&#13;
{&#13;
    public function purchase($userId, $ticketId)&#13;
    {&#13;
        $ticket = Ticket::find($ticketId);&#13;
&#13;
        if ($ticket-&amp;gt;get(&amp;#39;inventory&amp;#39;) &amp;lt; 0 ) {&#13;
            throw new LogicException(&amp;#39;ticket is sold out&amp;#39;);&#13;
        }&#13;
&#13;
        return Order::save([&#13;
            &amp;#39;user_id&amp;#39;=&amp;gt;$userId ,&#13;
            &amp;#39;ticket_id&amp;#39;=&amp;gt;$ticketId&#13;
        ]);&#13;
    }&#13;
}&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h2 id="toc_5"&gt;Why use a service class&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;So we have seen the benefits of using a service class:&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Easy to test similar to the fat model&lt;/li&gt;&#13;
&lt;li&gt;Easy to model the business logic&lt;/li&gt;&#13;
&lt;/ul&gt;</description><pubDate>Mon, 02 Mar 2020 07:31:03 +0000</pubDate></item><item><title>Debug MySQL slow query</title><link>https://www.startutorial.com/articles/view/debug-mysql-slow-query</link><guid>https://www.startutorial.com/articles/view/debug-mysql-slow-query<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;Slow MySQL query is a common cause of the application bottleneck. Slow queries are often discovered when a large dataset is added, which means they often happen in a production environment. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;In this tutorial, we will learn how to debug slow MySQL queries. &lt;/p&gt;&#13;
&#13;
&#13;
&#13;
&lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&lt;ol class="well"&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_1"&gt;Enable MySQL slow query log&lt;/a&gt;                 &#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_2"&gt;Clean up&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_3"&gt;More useful techniques&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_4"&gt;The end&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;/ol&gt;&#13;
&#13;
&#13;
&lt;h6 id="toc_1"&gt;Enable MySQL slow query log&lt;/h6&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Login to MySQL by running the command below:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;mysql -u root -p&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Select the database you are trying to debug:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;use my_database&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Enable slow query log: &lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;SET GLOBAL slow_query_log = &amp;#39;ON’;&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Set the query running time threshold in seconds:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;SET GLOBAL long_query_time = X;&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;We can verify if the settings are done properly by running the command below:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;show variables like &amp;#39;%slow%’;&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;The command above would show the log file path as well.&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Test if the logging is working:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;SELECT SLEEP(X);&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;The log file should show a log belongs to the query above.&lt;/p&gt;&#13;
&#13;
&lt;p&gt;Now we have successfully enabled MySQL slow query log and we can now investigate and debug which query is causing the problem.&lt;/p&gt;&#13;
&#13;
&lt;h6 id="toc_2"&gt;Clean up&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;When we have identified the problem, always remember to turn off the slow query log since it would add additional time to each query we run. &lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;We can run the command below to turn it off:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;SET GLOBAL slow_query_log = ‘OFF’;&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Verify if it is turned off successfully:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;show variables like &amp;#39;%slow%’;&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_3"&gt;More useful techniques&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;We also introduce some useful MySQL commands you may find useful.&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Running query without cache by adding the keyword SQL&lt;em&gt;NO&lt;/em&gt;CACHE:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;select SQL_NO_CACHE * from mytable where 1 limit 1;&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_4"&gt;The end&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;We hope you find this tutorial helpful.&lt;/p&gt;&#13;
</description><pubDate>Sun, 02 Feb 2020 02:04:43 +0000</pubDate></item><item><title>How to search JSON data in MySQL</title><link>https://www.startutorial.com/articles/view/how-to-search-json-data-in-mysql</link><guid>https://www.startutorial.com/articles/view/how-to-search-json-data-in-mysql<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;As of MySQL 5.7.8, MySQL supports a native JSON data type. In this tutorial, we will learn how to search for JSON data in MySQL.&lt;/p&gt;&#13;
&#13;
&lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&lt;ol class="well"&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_1"&gt;Sample data&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_2"&gt;Select a JSON field&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_3"&gt;Remove double quotes from selection result&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_4"&gt;Use dot notation in the selection path&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_5"&gt;Use the selected field as a condition&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_6"&gt;The end&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;/ol&gt;&#13;
&#13;
&lt;h6 id="toc_1"&gt;Sample data&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;For demonstration purpose, suppose we have created a database table with the following data:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;+-------------------------------+&#13;
| data                          | &#13;
+-------------------------------+&#13;
| {&amp;quot;id&amp;quot;: &amp;quot;4&amp;quot;, &amp;quot;name&amp;quot;: &amp;quot;Betty&amp;quot;,&amp;quot;mobile_no.&amp;quot;:&amp;quot;921213&amp;quot;}  | &#13;
+-------------------------------+&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;The column &amp;quot;data&amp;quot; is a JSON type. It currently holds a user JSON data with three fields:&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;id&lt;/li&gt;&#13;
&lt;li&gt;name&lt;/li&gt;&#13;
&lt;li&gt;mobile_no.&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;h6 id="toc_2"&gt;Select a JSON field&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;To select a particular field from JSON, we can use the JSON_EXTRACT function. For example, to select the name field:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;SELECT JSON_EXTRACT(data,&amp;#39;$.name&amp;#39;) AS  name FROM users;&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;This will output&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;&amp;quot;Betty&amp;quot;&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_3"&gt;Remove double quotes from selection result&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;You may have noticed double quotes in the previous sample. To remove the double quotes from the selection result, we can use JSON_UNQUOTE function:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;SELECT JSON_UNQUOTE(JSON_EXTRACT(data,&amp;#39;$.name&amp;#39;)) AS  name FROM users;&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;This will output&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;pre&gt;&lt;code class="language-none"&gt;Betty&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_4"&gt;Use dot notation in the selection path&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;In our sample data, it contains a JSON field called &amp;quot;mobile_no.&amp;quot;, pay attention to the ending dot notation. You cannot use the dot notation directly in the selection field, because it will be treated as a denominator. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;To use dot notation  in the selection path, we can wrap it with double quotes: &lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;SELECT JSON_UNQUOTE(JSON_EXTRACT(data,&amp;#39;$.&amp;quot;mobile_no.&amp;quot;&amp;#39;)) AS  mobile FROM users;&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;This will output:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;921213&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_5"&gt;Use the selected field as a condition&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;It is common to use the selected JSON field as a condition. To do this, we can use the HAVING clause:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;script type="syntaxhighlighter" class="brush: php"&gt;SELECT JSON_UNQUOTE(JSON_EXTRACT(data,&amp;#39;$.id&amp;#39;)) AS  id FROM users HAVING id = 1;&lt;/script&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_6"&gt;The end&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;We hope you find this tutorial helpful!&lt;/p&gt;&#13;
&#13;
</description><pubDate>Sun, 02 Feb 2020 01:58:19 +0000</pubDate></item><item><title>PHP Generator - reading file content</title><link>https://www.startutorial.com/articles/view/php-generator-reading-file-content</link><guid>https://www.startutorial.com/articles/view/php-generator-reading-file-content<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;In PHP, to fetch content from a file, a common implementation is to loop its content and store them in a temporary variable. In today&amp;#39;s tutorial, we want to introduce a solution by using the generator. &lt;/p&gt;&#13;
&#13;
&lt;h2 id="toc_1"&gt;Read file using a loop&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;Normal we will load the file content to memory and read its content using a loop. &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;$m1 = memory_get_peak_usage();&#13;
foreach (file(&amp;#39;lorem.txt&amp;#39;) as $l);&#13;
$m2 = memory_get_peak_usage(); &#13;
echo $m2 - $m1.&amp;quot;\n&amp;quot;; &#13;
&#13;
// Output&#13;
1542736&lt;/script&gt;&#13;
&#13;
&lt;h2 id="toc_2"&gt;Read file using a generator&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;We can do the same using a generator function.  Inside the function,  we open the file and yield its content line by line:&lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;function file_lines($filename) {&#13;
    $file = fopen($filename, &amp;#39;r&amp;#39;); &#13;
    while (($line = fgets($file)) !== false) {&#13;
        yield $line; &#13;
    } &#13;
    fclose($file); &#13;
}&#13;
&#13;
&#13;
$m1 = memory_get_peak_usage();&#13;
foreach (file_lines(&amp;#39;lorem.txt&amp;#39;) as $l);&#13;
$m2 = memory_get_peak_usage(); &#13;
echo $m2 - $m1.&amp;quot;\n&amp;quot;; &#13;
&#13;
// Ouput&#13;
0&lt;/script&gt;&#13;
&#13;
&lt;h2 id="toc_3"&gt;Generator&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;As we can see, when using a generator, we have greatly reduced memory usage. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;The reason is that when we &lt;strong&gt;yield&lt;/strong&gt; results from a generator function, it saves its current state until it is called next time. &lt;/p&gt;&#13;
&#13;
&lt;h2 id="toc_4"&gt;The end&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;Hopefully this simple tutorial helped you with your development.&lt;/p&gt;&#13;
&#13;
</description><pubDate>Tue, 07 Jan 2020 06:56:29 +0000</pubDate></item><item><title>PHP Generator - processing dataset</title><link>https://www.startutorial.com/articles/view/php-generator-processing-dataset</link><guid>https://www.startutorial.com/articles/view/php-generator-processing-dataset<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;In PHP, to work with a dataset, the natural thing to do is to use a loop, store the result to an array and return it. In today&amp;#39;s tutorial, we introduce a solution by using a generator. &lt;/p&gt;&#13;
&#13;
&lt;h2 id="toc_1"&gt;Return in a loop&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;For demonstration purposes, imagine we need a function that returns a series of numbers from one to twenty. Typically we will solve it this way:&lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;function oneToTwenty()&#13;
{&#13;
    $result = [];&#13;
    for ($i = 1; $i &amp;lt;= 20; $i++) {&#13;
        $result[] = $i;&#13;
    }&#13;
    return $result;&#13;
}&lt;/script&gt;&#13;
&#13;
&lt;p&gt;However, storing a large set of data into an array is memory intensive. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;We can do a simple benchmark by checking the memory used at run time:&lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;$base = memory_get_usage();&#13;
foreach (oneToTwenty() as $i) {&#13;
    echo $i . &amp;#39;:&amp;#39;;&#13;
    echo memory_get_usage() - $base;&#13;
    echo &amp;quot;\n&amp;quot;;&#13;
}&lt;/script&gt;&#13;
&#13;
&lt;p&gt;The output is:&lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;1:1368&#13;
2:1368&#13;
3:1368&#13;
4:1368&#13;
5:1368&#13;
6:1368&#13;
7:1368&#13;
8:1368&#13;
9:1368&#13;
10:1368&#13;
11:1368&#13;
12:1368&#13;
13:1368&#13;
14:1368&#13;
15:1368&#13;
16:1368&#13;
17:1368&#13;
18:1368&#13;
19:1368&#13;
20:1368&lt;/script&gt;&#13;
&#13;
&lt;p&gt;As we can see the memory used while looping the result set is about 1368 byte. &lt;/p&gt;&#13;
&#13;
&lt;h2 id="toc_2"&gt;Yield in a loop&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;We can solve the problem using a generator, and the only difference is that we use yield instead of return: &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;function oneToTwenty()&#13;
{&#13;
    for ($i = 1; $i &amp;lt;= 20; $i++) {&#13;
        yield $i;&#13;
    }&#13;
}&lt;/script&gt;&#13;
&#13;
&lt;p&gt;And let&amp;#39;s run the benchmark again, the output is shown s as below:&lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;1:672&#13;
2:672&#13;
3:672&#13;
4:672&#13;
5:672&#13;
6:672&#13;
7:672&#13;
8:672&#13;
9:672&#13;
10:672&#13;
11:672&#13;
12:672&#13;
13:672&#13;
14:672&#13;
15:672&#13;
16:672&#13;
17:672&#13;
18:672&#13;
19:672&#13;
20:672&#13;
&lt;/script&gt;&#13;
&#13;
&lt;p&gt;As we can see, we are using far less memory when using a generator.&lt;/p&gt;&#13;
&#13;
&lt;h2 id="toc_3"&gt;The end&lt;/h2&gt;&#13;
&#13;
&lt;p&gt;There is one pitfall when using a generator though, we need to be aware, we are trading the speed with the memory utilization. It is like everything else in programming, there is no right solution but trade-offs.&lt;/p&gt;&#13;
</description><pubDate>Tue, 07 Jan 2020 06:49:42 +0000</pubDate></item><item><title>How to Build a PHP Booking Calendar with MySQL</title><link>https://www.startutorial.com/articles/view/how-to-build-a-php-booking-calendar-with-mysql</link><guid>https://www.startutorial.com/articles/view/how-to-build-a-php-booking-calendar-with-mysql<isPermaLink>true</isPermaLink></guid><description>&lt;p&gt;In this tutorial, we will build a nice booking calendar using PHP and MySQL. Booking calendars are very common applications, you will learn how to write PHP code that separates business logic from presentation through this tutorial. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;After this tutorial, you should be able to build a working booking calendar as shown below:&lt;/p&gt;&#13;
&#13;
&lt;p class="text-center well"&gt;&lt;img src="https://www.startutorial.com/img/booking-calendar-tutorial.gif" class="img-responsive" style="margin:0 auto;"/&gt;&lt;/p&gt;&#13;
&#13;
&#13;
&#13;
&lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&lt;ol class="well"&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_2"&gt;Prepare the database&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;&#13;
    &lt;a href="#toc_3"&gt;Build a Booking class&lt;/a&gt;                              &#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_4"&gt;Build a Calendar class&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_5"&gt;Putting it Together&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;li&gt;                                        &#13;
    &lt;a href="#toc_6"&gt;Final and Source Code&lt;/a&gt;&#13;
&lt;/li&gt;&#13;
&lt;/ol&gt;&#13;
&#13;
&lt;h6 id="toc_2"&gt;1. Prepare the database&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;All the booking dates will be stored inside the MySQL database. Let&amp;#39;s design a simple database table.&lt;/p&gt;&#13;
&#13;
&lt;p&gt;Run the SQL statement below from your database console to create a table: &lt;strong&gt;bookings&lt;/strong&gt;.  &lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;pre class="brush: sql;"&gt;CREATE TABLE bookings ( &#13;
    id int auto_increment, &#13;
    booking_date DATE, &#13;
    constraint pk_example primary key (id) &#13;
);&lt;/pre&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;All bookings will be stored inside the table above, and each booked date is saved inside &lt;strong&gt;booking_date&lt;/strong&gt; column.&lt;/p&gt;&#13;
&#13;
&lt;h6 id="toc_3"&gt;2. Build a Booking class&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;In this section, we will build a PHP class that interacts with the database. It is capable of listing all the bookings, inserting a booking as well as deleting a booking.&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Create a php file &lt;strong&gt;Booking.php&lt;/strong&gt; and place the code below:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;pre class="brush: php;"&gt;&amp;lt;?php&#13;
&#13;
class Booking&#13;
{&#13;
&#13;
    private $dbh;&#13;
&#13;
    private $bookingsTableName = &amp;#39;bookings&amp;#39;;&#13;
&#13;
    /**&#13;
     * Booking constructor.&#13;
     * @param string $database&#13;
     * @param string $host&#13;
     * @param string $databaseUsername&#13;
     * @param string $databaseUserPassword&#13;
     */&#13;
    public function __construct($database, $host, $databaseUsername, $databaseUserPassword)&#13;
    {&#13;
        try {&#13;
&#13;
            $this-&amp;gt;dbh =&#13;
                new PDO(sprintf(&amp;#39;mysql:host=%s;dbname=%s&amp;#39;, $host, $database),&#13;
                    $databaseUsername,&#13;
                    $databaseUserPassword&#13;
                );&#13;
&#13;
        } catch (PDOException $e) {&#13;
            die($e-&amp;gt;getMessage());&#13;
        }&#13;
    }&#13;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;The code above will connect to a database when it is instantiated using PDO. When working with a database in PHP, we should always use PDO as it provides great security and friendly API.&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Create a function &lt;strong&gt;index()&lt;/strong&gt; inside the &lt;strong&gt;Booking&lt;/strong&gt; class:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;pre class="brush: php;"&gt;public function index()&#13;
{&#13;
    $statement = $this-&amp;gt;dbh-&amp;gt;query(&amp;#39;SELECT * FROM &amp;#39; . $this-&amp;gt;bookingsTableName);&#13;
    return $statement-&amp;gt;fetchAll(PDO::FETCH_ASSOC);&#13;
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;This function will list out all the booking records and return them as an associated array.&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Create a function &lt;strong&gt;add()&lt;/strong&gt; inside the &lt;strong&gt;Booking&lt;/strong&gt; class:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;pre class="brush: php;"&gt;public function add(DateTimeImmutable $bookingDate)&#13;
{&#13;
    $statement = $this-&amp;gt;dbh-&amp;gt;prepare(&#13;
        &amp;#39;INSERT INTO &amp;#39; . $this-&amp;gt;bookingsTableName . &amp;#39; (booking_date) VALUES (:bookingDate)&amp;#39;&#13;
    );&#13;
&#13;
    if (false === $statement) {&#13;
        throw new Exception(&amp;#39;Invalid prepare statement&amp;#39;);&#13;
    }&#13;
&#13;
    if (false === $statement-&amp;gt;execute([&#13;
            &amp;#39;:bookingDate&amp;#39; =&amp;gt; $bookingDate-&amp;gt;format(&amp;#39;Y-m-d&amp;#39;),&#13;
        ])) {&#13;
        throw new Exception(implode(&amp;#39; &amp;#39;, $statement-&amp;gt;errorInfo()));&#13;
    }&#13;
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;This function inserts a booking into the &lt;strong&gt;bookings&lt;/strong&gt; table. We are using PDO&amp;#39;s prepare statements to do the insertion, which provides auto escaping. &lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Create a function &lt;strong&gt;delete()&lt;/strong&gt; inside the &lt;strong&gt;Booking&lt;/strong&gt; class:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;pre class="brush: php;"&gt;public function delete($id)&#13;
{&#13;
    $statement = $this-&amp;gt;dbh-&amp;gt;prepare(&#13;
        &amp;#39;DELETE from &amp;#39; . $this-&amp;gt;bookingsTableName . &amp;#39; WHERE id = :id&amp;#39;&#13;
    );&#13;
    if (false === $statement) {&#13;
        throw new Exception(&amp;#39;Invalid prepare statement&amp;#39;);&#13;
    }&#13;
    if (false === $statement-&amp;gt;execute([&amp;#39;:id&amp;#39; =&amp;gt; $id])) {&#13;
        throw new Exception(implode(&amp;#39; &amp;#39;, $statement-&amp;gt;errorInfo()));&#13;
    }&#13;
}&#13;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;This function deletes a booking from the &lt;strong&gt;bookings&lt;/strong&gt; table by taking the primary key. &lt;/p&gt;&#13;
&#13;
&lt;p&gt;That is all for Booking class, and the complete &lt;strong&gt;Booking.php&lt;/strong&gt; is shown as below:&lt;/p&gt;&#13;
&#13;
&lt;div&gt;&lt;pre class="brush: php;"&gt;&amp;lt;?php&#13;
&#13;
&#13;
class Booking&#13;
{&#13;
&#13;
    private $dbh;&#13;
&#13;
    private $bookingsTableName = &amp;#39;bookings&amp;#39;;&#13;
&#13;
    /**&#13;
     * Booking constructor.&#13;
     * @param string $database&#13;
     * @param string $host&#13;
     * @param string $databaseUsername&#13;
     * @param string $databaseUserPassword&#13;
     */&#13;
    public function __construct($database, $host, $databaseUsername, $databaseUserPassword)&#13;
    {&#13;
        try {&#13;
&#13;
            $this-&amp;gt;dbh =&#13;
                new PDO(sprintf(&amp;#39;mysql:host=%s;dbname=%s&amp;#39;, $host, $database),&#13;
                    $databaseUsername,&#13;
                    $databaseUserPassword&#13;
                );&#13;
&#13;
        } catch (PDOException $e) {&#13;
            die($e-&amp;gt;getMessage());&#13;
        }&#13;
    }&#13;
&#13;
    public function index()&#13;
    {&#13;
        $statement = $this-&amp;gt;dbh-&amp;gt;query(&amp;#39;SELECT * FROM &amp;#39; . $this-&amp;gt;bookingsTableName);&#13;
        return $statement-&amp;gt;fetchAll(PDO::FETCH_ASSOC);&#13;
    }&#13;
&#13;
    public function add(DateTimeImmutable $bookingDate)&#13;
    {&#13;
        $statement = $this-&amp;gt;dbh-&amp;gt;prepare(&#13;
            &amp;#39;INSERT INTO &amp;#39; . $this-&amp;gt;bookingsTableName . &amp;#39; (booking_date) VALUES (:bookingDate)&amp;#39;&#13;
        );&#13;
&#13;
        if (false === $statement) {&#13;
            throw new Exception(&amp;#39;Invalid prepare statement&amp;#39;);&#13;
        }&#13;
&#13;
        if (false === $statement-&amp;gt;execute([&#13;
                &amp;#39;:bookingDate&amp;#39; =&amp;gt; $bookingDate-&amp;gt;format(&amp;#39;Y-m-d&amp;#39;),&#13;
            ])) {&#13;
            throw new Exception(implode(&amp;#39; &amp;#39;, $statement-&amp;gt;errorInfo()));&#13;
        }&#13;
    }&#13;
&#13;
    public function delete($id)&#13;
    {&#13;
        $statement = $this-&amp;gt;dbh-&amp;gt;prepare(&#13;
            &amp;#39;DELETE from &amp;#39; . $this-&amp;gt;bookingsTableName . &amp;#39; WHERE id = :id&amp;#39;&#13;
        );&#13;
        if (false === $statement) {&#13;
            throw new Exception(&amp;#39;Invalid prepare statement&amp;#39;);&#13;
        }&#13;
        if (false === $statement-&amp;gt;execute([&amp;#39;:id&amp;#39; =&amp;gt; $id])) {&#13;
            throw new Exception(implode(&amp;#39; &amp;#39;, $statement-&amp;gt;errorInfo()));&#13;
        }&#13;
    }&#13;
&#13;
}&#13;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_4"&gt;3. Build a Calendar class&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;In &lt;a href="https://www.startutorial.com/articles/view/php-calendar-class-with-hooks"&gt;one&lt;/a&gt; of our previous tutorials, we have built a powerful calendar class that comes with hooks. In this tutorial, we will utilize it to accomplish our goal. &lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Create a file &lt;strong&gt;Calendar.php&lt;/strong&gt;, copy and paste the following code:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;pre class="brush: php;"&gt;&amp;lt;?php&#13;
&#13;
class Calendar&#13;
{&#13;
&#13;
    /**&#13;
     * Constructor&#13;
     */&#13;
    public function __construct()&#13;
    {&#13;
        $this-&amp;gt;naviHref = htmlentities($_SERVER[&amp;#39;PHP_SELF&amp;#39;]);&#13;
    }&#13;
&#13;
    /********************* PROPERTY ********************/&#13;
    public $cellContent = &amp;#39;&amp;#39;;&#13;
    protected $observers = array();&#13;
&#13;
    private $dayLabels = array(&amp;quot;Mon&amp;quot;, &amp;quot;Tue&amp;quot;, &amp;quot;Wed&amp;quot;, &amp;quot;Thu&amp;quot;, &amp;quot;Fri&amp;quot;, &amp;quot;Sat&amp;quot;, &amp;quot;Sun&amp;quot;);&#13;
    private $currentYear = 0;&#13;
    private $currentMonth = 0;&#13;
    private $currentDay = 0;&#13;
    private $currentDate = null;&#13;
    private $daysInMonth = 0;&#13;
    private $sundayFirst = true;&#13;
    private $naviHref = null;&#13;
&#13;
    /********************* PUBLIC **********************/&#13;
    /* @return void&#13;
     * @access public&#13;
     */&#13;
    public function attachObserver($type, $observer)&#13;
    {&#13;
        $this-&amp;gt;observers[$type][] = $observer;&#13;
    }&#13;
&#13;
    /*&#13;
    *&#13;
    * @return void&#13;
    * @access public&#13;
    */&#13;
    public function notifyObserver($type)&#13;
    {&#13;
        if (isset($this-&amp;gt;observers[$type])) {&#13;
            foreach ($this-&amp;gt;observers[$type] as $observer) {&#13;
                $observer-&amp;gt;update($this);&#13;
            }&#13;
        }&#13;
    }&#13;
&#13;
    public function getCurrentDate()&#13;
    {&#13;
        return $this-&amp;gt;currentDate;&#13;
    }&#13;
&#13;
    /**&#13;
     * Set week labels&amp;#39; order.&#13;
     * When it is set to false,&#13;
     * monday will be listed as the first day.&#13;
     *&#13;
     * @param boolean&#13;
     * @return              void&#13;
     * @author              The-Di-Lab &amp;lt;thedilab@gmail.com&amp;gt;&#13;
     * @access              public&#13;
     */&#13;
    public function setSundayFirst($bool = true)&#13;
    {&#13;
        $this-&amp;gt;sundayFirst = $bool;&#13;
    }&#13;
&#13;
    /**&#13;
     * print out the calendar&#13;
     *&#13;
     * @param string&#13;
     * @param string&#13;
     * @param array&#13;
     * @return              string&#13;
     * @author              The-Di-Lab &amp;lt;thedilab@gmail.com&amp;gt;&#13;
     * @access              public&#13;
     */&#13;
    public function show($month = null, $year = null, $attributes = false)&#13;
    {&#13;
        if (null == $year &amp;amp;&amp;amp; isset($_GET[&amp;#39;year&amp;#39;])) {&#13;
            $year = $_GET[&amp;#39;year&amp;#39;];&#13;
        } else if (null == $year) {&#13;
            $year = date(&amp;quot;Y&amp;quot;, time());&#13;
        }&#13;
&#13;
        if (null == $month &amp;amp;&amp;amp; isset($_GET[&amp;#39;month&amp;#39;])) {&#13;
            $month = $_GET[&amp;#39;month&amp;#39;];&#13;
        } else if (null == $month) {&#13;
            $month = date(&amp;quot;m&amp;quot;, time());&#13;
        }&#13;
&#13;
        $this-&amp;gt;currentYear = $year;&#13;
        $this-&amp;gt;currentMonth = $month;&#13;
        $this-&amp;gt;daysInMonth = $this-&amp;gt;_daysInMonth($month, $year);&#13;
&#13;
        $content = &amp;#39;&amp;lt;div id=&amp;quot;calendar&amp;quot;&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;div class=&amp;quot;box&amp;quot;&amp;gt;&amp;#39; .&#13;
            $this-&amp;gt;_createNavi() .&#13;
            &amp;#39;&amp;lt;/div&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;div class=&amp;quot;box-content&amp;quot;&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;ul class=&amp;quot;label&amp;quot;&amp;gt;&amp;#39; . $this-&amp;gt;_createLabels() . &amp;#39;&amp;lt;/ul&amp;gt;&amp;#39;;&#13;
        $content .= &amp;#39;&amp;lt;div class=&amp;quot;clear&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&amp;#39;;&#13;
        $content .= &amp;#39;&amp;lt;ul class=&amp;quot;dates&amp;quot;&amp;gt;&amp;#39;;&#13;
        for ($i = 0; $i &amp;lt; $this-&amp;gt;_weeksInMonth($month, $year); $i++) {&#13;
            for ($j = 1; $j &amp;lt;= 7; $j++) {&#13;
                $content .= $this-&amp;gt;_showDay($i * 7 + $j, $attributes);&#13;
            }&#13;
        }&#13;
        $content .= &amp;#39;&amp;lt;/ul&amp;gt;&amp;#39;;&#13;
        $content .= &amp;#39;&amp;lt;div class=&amp;quot;clear&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&amp;#39;;&#13;
        $content .= &amp;#39;&amp;lt;/div&amp;gt;&amp;#39;;&#13;
        $content .= &amp;#39;&amp;lt;/div&amp;gt;&amp;#39;;&#13;
        return $content;&#13;
    }&#13;
&#13;
    /********************* PRIVATE **********************/&#13;
    /**&#13;
     * create the li element for ul&#13;
     *&#13;
     * @param string&#13;
     * @param array&#13;
     * @return              string&#13;
     * @author              The-Di-Lab &amp;lt;thedilab@gmail.com&amp;gt;&#13;
     * @access              private&#13;
     */&#13;
    private function _showDay($cellNumber, $attributes = false)&#13;
    {&#13;
        if ($this-&amp;gt;currentDay == 0) {&#13;
            //1 (for Monday) through 7 (for Sunday)&#13;
            $firstDayOfTheWeek = date(&amp;#39;N&amp;#39;, strtotime($this-&amp;gt;currentYear . &amp;#39;-&amp;#39; . $this-&amp;gt;currentMonth . &amp;#39;-01&amp;#39;));&#13;
            if ($this-&amp;gt;sundayFirst) {&#13;
                if ($firstDayOfTheWeek == 7) {&#13;
                    $firstDayOfTheWeek = 1;&#13;
                } else {&#13;
                    $firstDayOfTheWeek++;&#13;
                }&#13;
            }&#13;
            if (intval($cellNumber) == intval($firstDayOfTheWeek)) {&#13;
                $this-&amp;gt;currentDay = 1;&#13;
            }&#13;
        }&#13;
&#13;
        if (($this-&amp;gt;currentDay != 0) &amp;amp;&amp;amp; ($this-&amp;gt;currentDay &amp;lt;= $this-&amp;gt;daysInMonth)) {&#13;
            $this-&amp;gt;currentDate = date(&amp;#39;Y-m-d&amp;#39;, strtotime($this-&amp;gt;currentYear . &amp;#39;-&amp;#39; . $this-&amp;gt;currentMonth . &amp;#39;-&amp;#39; . ($this-&amp;gt;currentDay)));&#13;
            $cellContent = $this-&amp;gt;_createCellContent($attributes);&#13;
            $this-&amp;gt;currentDay++;&#13;
        } else {&#13;
            $this-&amp;gt;currentDate = null;&#13;
            $cellContent = null;&#13;
        }&#13;
&#13;
&#13;
        return &amp;#39;&amp;lt;li id=&amp;quot;li-&amp;#39; . $this-&amp;gt;currentDate . &amp;#39;&amp;quot; class=&amp;quot;&amp;#39; . ($cellNumber % 7 == 1 ? &amp;#39; start &amp;#39; : ($cellNumber % 7 == 0 ? &amp;#39; end &amp;#39; : &amp;#39; &amp;#39;)) .&#13;
            ($cellContent == null ? &amp;#39;mask&amp;#39; : &amp;#39;&amp;#39;) . &amp;#39;&amp;quot;&amp;gt;&amp;#39; . $cellContent . &amp;#39;&amp;lt;/li&amp;gt;&amp;#39;;&#13;
    }&#13;
&#13;
    /**&#13;
     * create navigation&#13;
     *&#13;
     * @return              string&#13;
     * @author              The-Di-Lab &amp;lt;thedilab@gmail.com&amp;gt;&#13;
     * @access              private&#13;
     */&#13;
    private function _createNavi()&#13;
    {&#13;
        $nextMonth = $this-&amp;gt;currentMonth == 12 ? 1 : intval($this-&amp;gt;currentMonth) + 1;&#13;
        $nextYear = $this-&amp;gt;currentMonth == 12 ? intval($this-&amp;gt;currentYear) + 1 : $this-&amp;gt;currentYear;&#13;
&#13;
        $preMonth = $this-&amp;gt;currentMonth == 1 ? 12 : intval($this-&amp;gt;currentMonth) - 1;&#13;
        $preYear = $this-&amp;gt;currentMonth == 1 ? intval($this-&amp;gt;currentYear) - 1 : $this-&amp;gt;currentYear;&#13;
&#13;
        return&#13;
            &amp;#39;&amp;lt;div class=&amp;quot;header&amp;quot;&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;a class=&amp;quot;prev&amp;quot; href=&amp;quot;&amp;#39; . $this-&amp;gt;naviHref . &amp;#39;?month=&amp;#39; . sprintf(&amp;#39;%02d&amp;#39;, $preMonth) . &amp;#39;&amp;amp;year=&amp;#39; . $preYear . &amp;#39;&amp;quot;&amp;gt;Prev&amp;lt;/a&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;span class=&amp;quot;title&amp;quot;&amp;gt;&amp;#39; . date(&amp;#39;Y M&amp;#39;, strtotime($this-&amp;gt;currentYear . &amp;#39;-&amp;#39; . $this-&amp;gt;currentMonth . &amp;#39;-1&amp;#39;)) . &amp;#39;&amp;lt;/span&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;a class=&amp;quot;next&amp;quot; href=&amp;quot;&amp;#39; . $this-&amp;gt;naviHref . &amp;#39;?month=&amp;#39; . sprintf(&amp;quot;%02d&amp;quot;, $nextMonth) . &amp;#39;&amp;amp;year=&amp;#39; . $nextYear . &amp;#39;&amp;quot;&amp;gt;Next&amp;lt;/a&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;/div&amp;gt;&amp;#39;;&#13;
    }&#13;
&#13;
    /**&#13;
     * create calendar week labels&#13;
     *&#13;
     * @return              string&#13;
     * @author              The-Di-Lab &amp;lt;thedilab@gmail.com&amp;gt;&#13;
     * @access              private&#13;
     */&#13;
    private function _createLabels()&#13;
    {&#13;
        if ($this-&amp;gt;sundayFirst) {&#13;
            $temp = $this-&amp;gt;dayLabels[0];&#13;
            for ($i = 1; $i &amp;lt; sizeof($this-&amp;gt;dayLabels); $i++) {&#13;
                $tmp = $this-&amp;gt;dayLabels[$i];&#13;
                $this-&amp;gt;dayLabels[$i] = $temp;&#13;
                $temp = $tmp;&#13;
            }&#13;
            $this-&amp;gt;dayLabels[0] = $temp;&#13;
        }&#13;
&#13;
&#13;
        $content = &amp;#39;&amp;#39;;&#13;
        foreach ($this-&amp;gt;dayLabels as $index =&amp;gt; $label) {&#13;
            $content .= &amp;#39;&amp;lt;li class=&amp;quot;&amp;#39; . ($label == 6 ? &amp;#39;end title&amp;#39; : &amp;#39;start title&amp;#39;) . &amp;#39; title&amp;quot;&amp;gt;&amp;#39; . $label . &amp;#39;&amp;lt;/li&amp;gt;&amp;#39;;&#13;
        }&#13;
&#13;
        return $content;&#13;
    }&#13;
&#13;
    /**&#13;
     * create content for li element&#13;
     *&#13;
     * @param array&#13;
     * @return              string&#13;
     * @author              The-Di-Lab &amp;lt;thedilab@gmail.com&amp;gt;&#13;
     * @access              private&#13;
     */&#13;
    private function _createCellContent($setting = false)&#13;
    {&#13;
        $this-&amp;gt;cellContent = &amp;#39;&amp;#39;;&#13;
&#13;
        $this-&amp;gt;cellContent = $this-&amp;gt;currentDay;&#13;
&#13;
        //observer&#13;
        $this-&amp;gt;notifyObserver(&amp;#39;showCell&amp;#39;);&#13;
&#13;
        return $this-&amp;gt;cellContent;&#13;
    }&#13;
&#13;
    /**&#13;
     * calculate number of weeks in a particular month&#13;
     *&#13;
     * @param number&#13;
     * @param number&#13;
     * @return              number&#13;
     * @author              The-Di-Lab &amp;lt;thedilab@gmail.com&amp;gt;&#13;
     * @access              private&#13;
     */&#13;
    private function _weeksInMonth($month = null, $year = null)&#13;
    {&#13;
        if (null == ($year))&#13;
            $year = date(&amp;quot;Y&amp;quot;, time());&#13;
&#13;
        if (null == ($month))&#13;
            $month = date(&amp;quot;m&amp;quot;, time());&#13;
&#13;
        // find number of weeks in this month&#13;
        $daysInMonths = $this-&amp;gt;_daysInMonth($month, $year);&#13;
&#13;
        $numOfweeks = ($daysInMonths % 7 == 0 ? 0 : 1) + intval($daysInMonths / 7);&#13;
        $monthEndingDay = date(&amp;#39;N&amp;#39;, strtotime($year . &amp;#39;-&amp;#39; . $month . &amp;#39;-&amp;#39; . $daysInMonths));&#13;
        $monthStartDay = date(&amp;#39;N&amp;#39;, strtotime($year . &amp;#39;-&amp;#39; . $month . &amp;#39;-01&amp;#39;));&#13;
        $monthEndingDay == 7 ? $monthEndingDay = 0 : &amp;#39;&amp;#39;;&#13;
        $monthStartDay == 7 ? $monthStartDay = 0 : &amp;#39;&amp;#39;;&#13;
&#13;
        if ($monthEndingDay &amp;lt; $monthStartDay) {&#13;
            $numOfweeks++;&#13;
        }&#13;
        return $numOfweeks;&#13;
&#13;
    }&#13;
&#13;
    /**&#13;
     * calculate number of days in a particular month&#13;
     *&#13;
     * @param number&#13;
     * @param number&#13;
     * @return              number&#13;
     * @author              The-Di-Lab &amp;lt;thedilab@gmail.com&amp;gt;&#13;
     * @access              private&#13;
     */&#13;
    private function _daysInMonth($month = null, $year = null)&#13;
    {&#13;
        if (null == ($year))&#13;
            $year = date(&amp;quot;Y&amp;quot;, time());&#13;
&#13;
        if (null == ($month))&#13;
            $month = date(&amp;quot;m&amp;quot;, time());&#13;
&#13;
        return date(&amp;#39;t&amp;#39;, strtotime($year . &amp;#39;-&amp;#39; . $month . &amp;#39;-01&amp;#39;));&#13;
    }&#13;
&#13;
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;We are not going to explore the details of this class, since we have already covered it at &lt;a href="https://www.startutorial.com/articles/view/php-calendar-class-with-hooks"&gt;https://www.startutorial.com/articles/view/php-calendar-class-with-hooks&lt;/a&gt;, feel free to read more there. &lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Create a file &lt;strong&gt;BookableCell.php&lt;/strong&gt;, copy and paste the following code:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;pre class="brush: php;"&gt;&amp;lt;?php&#13;
&#13;
&#13;
class BookableCell&#13;
{&#13;
    /**&#13;
     * @var Booking&#13;
     */&#13;
    private $booking;&#13;
&#13;
    private $currentURL;&#13;
&#13;
    /**&#13;
     * BookableCell constructor.&#13;
     * @param $booking&#13;
     */&#13;
    public function __construct(Booking $booking)&#13;
    {&#13;
        $this-&amp;gt;booking = $booking;&#13;
        $this-&amp;gt;currentURL = htmlentities($_SERVER[&amp;#39;REQUEST_URI&amp;#39;]);&#13;
    }&#13;
&#13;
    public function update(Calendar $cal)&#13;
    {&#13;
        if ($this-&amp;gt;isDateBooked($cal-&amp;gt;getCurrentDate())) {&#13;
            return $cal-&amp;gt;cellContent =&#13;
                $this-&amp;gt;bookedCell($cal-&amp;gt;getCurrentDate());&#13;
        }&#13;
&#13;
        if (!$this-&amp;gt;isDateBooked($cal-&amp;gt;getCurrentDate())) {&#13;
            return $cal-&amp;gt;cellContent =&#13;
                $this-&amp;gt;openCell($cal-&amp;gt;getCurrentDate());&#13;
        }&#13;
    }&#13;
&#13;
    public function routeActions()&#13;
    {&#13;
        if (isset($_POST[&amp;#39;delete&amp;#39;])) {&#13;
            $this-&amp;gt;deleteBooking($_POST[&amp;#39;id&amp;#39;]);&#13;
        }&#13;
&#13;
        if (isset($_POST[&amp;#39;add&amp;#39;])) {&#13;
            $this-&amp;gt;addBooking($_POST[&amp;#39;date&amp;#39;]);&#13;
        }&#13;
    }&#13;
&#13;
    private function openCell($date)&#13;
    {&#13;
        return &amp;#39;&amp;lt;div class=&amp;quot;open&amp;quot;&amp;gt;&amp;#39; . $this-&amp;gt;bookingForm($date) . &amp;#39;&amp;lt;/div&amp;gt;&amp;#39;;&#13;
    }&#13;
&#13;
    private function bookedCell($date)&#13;
    {&#13;
        return &amp;#39;&amp;lt;div class=&amp;quot;booked&amp;quot;&amp;gt;&amp;#39; . $this-&amp;gt;deleteForm($this-&amp;gt;bookingId($date)) . &amp;#39;&amp;lt;/div&amp;gt;&amp;#39;;&#13;
    }&#13;
&#13;
    private function isDateBooked($date)&#13;
    {&#13;
        return in_array($date, $this-&amp;gt;bookedDates());&#13;
    }&#13;
&#13;
    private function bookedDates()&#13;
    {&#13;
        return array_map(function ($record) {&#13;
            return $record[&amp;#39;booking_date&amp;#39;];&#13;
        }, $this-&amp;gt;booking-&amp;gt;index());&#13;
    }&#13;
&#13;
    private function bookingId($date)&#13;
    {&#13;
        $booking = array_filter($this-&amp;gt;booking-&amp;gt;index(), function ($record) use ($date) {&#13;
            return $record[&amp;#39;booking_date&amp;#39;] == $date;&#13;
        });&#13;
&#13;
        $result = array_shift($booking);&#13;
&#13;
        return $result[&amp;#39;id&amp;#39;];&#13;
    }&#13;
&#13;
    private function deleteBooking($id)&#13;
    {&#13;
        $this-&amp;gt;booking-&amp;gt;delete($id);&#13;
    }&#13;
&#13;
    private function addBooking($date)&#13;
    {&#13;
        $date = new DateTimeImmutable($date);&#13;
        $this-&amp;gt;booking-&amp;gt;add($date);&#13;
    }&#13;
&#13;
    private function bookingForm($date)&#13;
    {&#13;
        return&#13;
            &amp;#39;&amp;lt;form  method=&amp;quot;post&amp;quot; action=&amp;quot;&amp;#39; . $this-&amp;gt;currentURL . &amp;#39;&amp;quot;&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;add&amp;quot; /&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;date&amp;quot; value=&amp;quot;&amp;#39; . $date . &amp;#39;&amp;quot; /&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;input class=&amp;quot;submit&amp;quot; type=&amp;quot;submit&amp;quot; value=&amp;quot;Book&amp;quot; /&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;/form&amp;gt;&amp;#39;;&#13;
    }&#13;
&#13;
    private function deleteForm($id)&#13;
    {&#13;
        return&#13;
            &amp;#39;&amp;lt;form onsubmit=&amp;quot;return confirm(\&amp;#39;Are you sure to cancel?\&amp;#39;);&amp;quot; method=&amp;quot;post&amp;quot; action=&amp;quot;&amp;#39; . $this-&amp;gt;currentURL . &amp;#39;&amp;quot;&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;delete&amp;quot; /&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;id&amp;quot; value=&amp;quot;&amp;#39; . $id . &amp;#39;&amp;quot; /&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;input class=&amp;quot;submit&amp;quot; type=&amp;quot;submit&amp;quot; value=&amp;quot;Delete&amp;quot; /&amp;gt;&amp;#39; .&#13;
            &amp;#39;&amp;lt;/form&amp;gt;&amp;#39;;&#13;
    }&#13;
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;Two major APIs of this class we should take a look at:&lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Function &lt;strong&gt;update(Calendar $cal)&lt;/strong&gt;: this function is called when the &lt;strong&gt;Calendar&lt;/strong&gt; class renders each cell. We render different content for the cell depends on its booking status. If this date is booked, we will render a cell with a cancellation link, otherwise, we render a booking link. &lt;/li&gt;&#13;
&lt;li&gt;Function &lt;strong&gt;routeActions()&lt;/strong&gt;: this is a very simple routing function. It checks the &lt;strong&gt;$_POST&lt;/strong&gt; parameter and decides whether to delete a booking or add a booking.&lt;br&gt;&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;p&gt;The &lt;strong&gt;BookableCell&lt;/strong&gt; connects to the &lt;strong&gt;Calendar&lt;/strong&gt; class via a hook, we call &lt;strong&gt;BookableCell&lt;/strong&gt; a plugin for &lt;strong&gt;Calendar&lt;/strong&gt;. &lt;/p&gt;&#13;
&#13;
&lt;h6 id="toc_5"&gt;4. Putting it Together&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;Now it is time to put everything together and present our booking calendar to the world. &lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Create a file &lt;strong&gt;index.php&lt;/strong&gt; with the following code:&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;pre class="brush: php;"&gt;&amp;lt;html&amp;gt;&#13;
&amp;lt;head&amp;gt;&#13;
    &amp;lt;link href=&amp;quot;calendar.css&amp;quot; type=&amp;quot;text/css&amp;quot; rel=&amp;quot;stylesheet&amp;quot;/&amp;gt;&#13;
&amp;lt;/head&amp;gt;&#13;
&amp;lt;body&amp;gt;&#13;
&amp;lt;?php&#13;
include &amp;#39;Calendar.php&amp;#39;;&#13;
include &amp;#39;Booking.php&amp;#39;;&#13;
include &amp;#39;BookableCell.php&amp;#39;;&#13;
&#13;
&#13;
$booking = new Booking(&#13;
    &amp;#39;tutorial&amp;#39;,&#13;
    &amp;#39;localhost&amp;#39;,&#13;
    &amp;#39;root&amp;#39;,&#13;
    &amp;#39;&amp;#39;&#13;
);&#13;
&#13;
$bookableCell = new BookableCell($booking);&#13;
&#13;
$calendar = new Calendar();&#13;
&#13;
$calendar-&amp;gt;attachObserver(&amp;#39;showCell&amp;#39;, $bookableCell);&#13;
&#13;
$bookableCell-&amp;gt;routeActions();&#13;
&#13;
echo $calendar-&amp;gt;show();&#13;
?&amp;gt;&#13;
&amp;lt;/body&amp;gt;&#13;
&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#13;
&#13;
&lt;p&gt;Let&amp;#39;s go through the code above from top to bottom. &lt;/p&gt;&#13;
&#13;
&lt;ul&gt;&#13;
&lt;li&gt;Instantiate a &lt;strong&gt;BookableCell&lt;/strong&gt; plugin object.&lt;/li&gt;&#13;
&lt;li&gt;Instantiate a &lt;strong&gt;Calendar&lt;/strong&gt; object. &lt;/li&gt;&#13;
&lt;li&gt;Hook the &lt;strong&gt;BookableCell&lt;/strong&gt; object into &lt;strong&gt;Calendar&lt;/strong&gt; object.&lt;/li&gt;&#13;
&lt;li&gt;Call the &lt;strong&gt;BookableCell&lt;/strong&gt; object&amp;#39;s routing function.&lt;/li&gt;&#13;
&lt;li&gt;&lt;p&gt;Render the calendar. &lt;/p&gt;&lt;/li&gt;&#13;
&lt;li&gt;&lt;p&gt;Last missing puzzle is the css file, create a file &lt;strong&gt;calendar.css&lt;/strong&gt;, copy and paste the code below:&lt;/p&gt;&lt;/li&gt;&#13;
&lt;/ul&gt;&#13;
&#13;
&lt;div&gt;&lt;pre class="brush: php;"&gt;/*******************************Calendar Top Navigation*********************************/&#13;
body {&#13;
    font-family: &amp;quot;Arial&amp;quot;;&#13;
}&#13;
&#13;
div#calendar {&#13;
    margin: 0px auto;&#13;
    padding: 0px;&#13;
    width: 602px;&#13;
}&#13;
&#13;
div#calendar div.box {&#13;
    position: relative;&#13;
    top: 0px;&#13;
    left: 0px;&#13;
    width: 100%;&#13;
    height: 40px;&#13;
    background-color: #3FA7D6;&#13;
}&#13;
&#13;
div#calendar div.header {&#13;
    line-height: 40px;&#13;
    vertical-align: middle;&#13;
    position: absolute;&#13;
    left: 11px;&#13;
    top: 0px;&#13;
    width: 582px;&#13;
    height: 40px;&#13;
    text-align: center;&#13;
}&#13;
&#13;
div#calendar div.header a.prev, div#calendar div.header a.next {&#13;
    position: absolute;&#13;
    top: 0px;&#13;
    height: 17px;&#13;
    display: block;&#13;
    cursor: pointer;&#13;
    text-decoration: none;&#13;
    color: #FFF;&#13;
}&#13;
&#13;
div#calendar div.header span.title {&#13;
    color: #FFF;&#13;
    font-size: 18px;&#13;
}&#13;
&#13;
div#calendar div.header a.prev {&#13;
    left: 0px;&#13;
}&#13;
&#13;
div#calendar div.header a.next {&#13;
    right: 0px;&#13;
}&#13;
&#13;
/*******************************Calendar Content Cells*********************************/&#13;
div#calendar div.box-content {&#13;
    border: 1px solid #3FA7D6;&#13;
    border-top: none;&#13;
}&#13;
&#13;
div#calendar ul.label {&#13;
    float: left;&#13;
    margin: 0px;&#13;
    padding: 0px;&#13;
    margin-top: 5px;&#13;
    margin-left: 5px;&#13;
}&#13;
&#13;
div#calendar ul.label li {&#13;
    margin: 0px;&#13;
    padding: 0px;&#13;
    margin-right: 5px;&#13;
    float: left;&#13;
    list-style-type: none;&#13;
    width: 80px;&#13;
    height: 40px;&#13;
    line-height: 40px;&#13;
    vertical-align: middle;&#13;
    text-align: center;&#13;
    color: #000;&#13;
    font-size: 15px;&#13;
    background-color: transparent;&#13;
}&#13;
&#13;
div#calendar ul.dates {&#13;
    float: left;&#13;
    margin: 0px;&#13;
    padding: 0px;&#13;
    margin-left: 5px;&#13;
    margin-bottom: 5px;&#13;
}&#13;
&#13;
/** overall width = width+padding-right**/&#13;
div#calendar ul.dates li {&#13;
    margin: 0px;&#13;
    padding: 0px;&#13;
    margin-right: 5px;&#13;
    margin-top: 5px;&#13;
    line-height: 80px;&#13;
    vertical-align: middle;&#13;
    float: left;&#13;
    list-style-type: none;&#13;
    width: 80px;&#13;
    height: 80px;&#13;
    font-size: 25px;&#13;
    background-color: #FFF;&#13;
    color: #000;&#13;
    text-align: center;&#13;
    position: relative;&#13;
}&#13;
&#13;
:focus {&#13;
    outline: none;&#13;
}&#13;
&#13;
div.clear {&#13;
    clear: both;&#13;
}&#13;
&#13;
li div {&#13;
    display: flex;&#13;
}&#13;
&#13;
li div form {&#13;
    display: inline;&#13;
    align-self: center;&#13;
    margin: 0;&#13;
    position: absolute;&#13;
    bottom: 2px;&#13;
}&#13;
&#13;
div.open {&#13;
    background: #59CD90;&#13;
    width: 100%;&#13;
    height: 100%;&#13;
    display: flex;&#13;
    justify-content: center;&#13;
    flex-direction: column;&#13;
    text-align: center;&#13;
}&#13;
&#13;
div.booked {&#13;
    background: #D36135;&#13;
    width: 100%;&#13;
    height: 100%;&#13;
    display: flex;&#13;
    justify-content: center;&#13;
    flex-direction: column;&#13;
    text-align: center;&#13;
    line-height: inherit;&#13;
}&#13;
&#13;
.submit {&#13;
    box-shadow:inset 0px 1px 0px 0px #ffffff;&#13;
    background:linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);&#13;
    background-color:#ffffff;&#13;
    border-radius:3px;&#13;
    border:1px solid #dcdcdc;&#13;
    display:inline-block;&#13;
    cursor:pointer;&#13;
    color:#666666;&#13;
    font-size:10px;&#13;
    font-weight:bold;&#13;
    padding:3px 12px;&#13;
    text-decoration:none;&#13;
    text-shadow:0px 1px 0px #ffffff;&#13;
}&#13;
&#13;
.submit:hover {&#13;
    background:linear-gradient(to bottom, #f6f6f6 5%, #ffffff 100%);&#13;
    background-color:#f6f6f6;&#13;
}&#13;
.submit:active {&#13;
    position:relative;&#13;
    top:1px;&#13;
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&#13;
&#13;
&lt;h6 id="toc_6"&gt;5. Final and Source Code&lt;/h6&gt;&#13;
&#13;
&lt;p&gt;If you have followed along correctly. Head over to &lt;strong&gt;index.php&lt;/strong&gt; from your browser. You should see a beautiful PHP booking calendar as shown below:&lt;/p&gt;&#13;
&#13;
&lt;p class="text-center well"&gt;&lt;img src="https://www.startutorial.com/img/booking-calendar-tutorial.png" class="img-responsive" style="margin:0 auto;" /&gt;&lt;/p&gt;&#13;
&#13;
&lt;p&gt;If you follow along with the tutorials step by step, you will get all the source code in place. However, if you are feeling lazy or need to download the complete source code from us. You can do so by paying us a small fee. Your support will enable us to produce better and more in-depth tutorials.&lt;/p&gt;&#13;
&#13;
&lt;p class="text-center"&gt;&#13;
&lt;script src="https://gumroad.com/js/gumroad.js"&gt;&lt;/script&gt;&#13;
&lt;a class="gumroad-button" href="https://gum.co/xNYZw?wanted=true" target="_blank"&gt;Download Source Code ($9)&lt;/a&gt;&#13;
&lt;/p&gt;&#13;
&#13;
</description><pubDate>Thu, 17 Oct 2019 14:30:58 +0000</pubDate></item><item><title>Modern PHP Developer - TDD</title><link>https://www.startutorial.com/articles/view/modern-php-developer-tdd</link><guid>https://www.startutorial.com/articles/view/modern-php-developer-tdd<isPermaLink>true</isPermaLink></guid><description>                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;PHPUnit&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;TDD by example&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you have not heard of Test Driven Development(TDD), you should begin to familiarise yourself with&#13;
                    it. Though PHP community is a bit late on TDD practice compared to other languages such as Ruby,&#13;
                    once the benefits TDD were realized, it has become almost essential for a modern PHP developer.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    TDD is a software development technique. The basic idea behind TDD is that, we create tests before&#13;
                    we actually code any thing. Writing test against no code is more of a mindset shift than anything&#13;
                    else. It is opposite of traditional coding habit, where we create code first, then manually run the&#13;
                    unit to make sure it does what we intended manually. The benefits that TDD brings to us are&#13;
                    enormous. At first it forces us to think about code design before we create any concrete code, then&#13;
                    it allows us to refactor our code base without worrying about the side effect. It makes our code&#13;
                    easy to maintain in the long run.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    TDD consists of three phases: which are Red, Green and Refactor.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;Red phase&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In red phase, as the developer, we will plan out what the code will look like without actually&#13;
                    writing it. This is to say, we will design our class or class methods, without implementing its&#13;
                    details. Initially this phase is hard, it requires us to change our traditional habit of coding. But&#13;
                    once we get used to this process, we will naturally adapt to it and realize that it helps us design&#13;
                    better code. It is about changing our mindset, as we should focus on the input and output of the&#13;
                    API, instead of the details of the code. The result of this phase is successful creation of red&#13;
                    test.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;Green phase&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In green phase, it is all about writing the quickest piece of code to pass the tests. In this phase,&#13;
                    we should not spend too much making the code clean or refactoring. Though we all want to write the&#13;
                    most beautiful piece of code, that is not the task at hand in this phase. The result of this phase&#13;
                    is green tests.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;Refactor phase&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In refactor phase, we focus on making the code clean. Since we have tests created above to guard&#13;
                    bugs from side effects, we gain confidence for carrying out refactor. If by chance, a bug is&#13;
                    introduced from refactoring, our tests will report it as soon as it appears. So the&#13;
                    natural way of refactor is to run the test as soon as you have modified any code.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. PHPUnit&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    TDD lets us test drive our development cycle. When practicing TDD in PHP, obviously we need to&#13;
                    define the kind of test we will do. The most common test in TDD is Unit Test which tests the&#13;
                    smallest testable parts of an application it considers a unit, which is typically a class method.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now imagine writing unit tests manually and building an automated method to run them. It is&#13;
                    definitely a lot of work. Fortunately, there are already unit testing frameworks out there for us to&#13;
                    use. Among a number of unit testing frameworks, PHPUnit is the most popular one and it is widely&#13;
                    used in the PHP community.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;Getting started with PHPUnit&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;Installation&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The easiest way to install PHPUnit is via Composer. Open up your terminal and in your project&#13;
                    folder,&#13;
                    simply run composer require phpunit/phpunit .&#13;
                    By default, the bin file of PHPUnit will be placed into vendor/bin folder,&#13;
                    so we can run vendor/bin/phpunit directly from our project's root folder.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;Your first unit test&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Time to create your first unit test! Before doing so, we need a class to test. Let's create a very&#13;
                    simple class called Calculator and write a test for it.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Create a file with the name of Calculator.php and copy the code below to the file. This Calculator&#13;
                    class only has an Add function. :&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
class Calculator&#13;
{&#13;
    public function add($a, $b)&#13;
    {&#13;
        return $a + $b;&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Create the test file CalculatorTest.php, and copy the code below to the file. We will explain each&#13;
                    function in details.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
require 'Calculator.php';&#13;
class CalculatorTest extends PHPUnit_Framework_TestCase&#13;
{&#13;
    private $calculator;&#13;
&#13;
    protected function setUp()&#13;
    {&#13;
        $this-&gt;calculator = new Calculator();&#13;
    }&#13;
&#13;
    protected function tearDown()&#13;
    {&#13;
        $this-&gt;calculator = NULL;&#13;
    }&#13;
&#13;
    public function testAdd()&#13;
    {&#13;
        $result = $this-&gt;calculator-&gt;add(1, 2);&#13;
        $this-&gt;assertEquals(3, $result);&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&#13;
                        Line 2: Includes class file Calculator.php. This is the class that we are going to test against,&#13;
                        so make sure you include it.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Line 8: setUp() is called before each test runs. Keep in mind that it runs before each test,&#13;
                        which means, if you have another test function, it too will run setUp() before.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Line 13: Similar to setUp() , tearDown() is called after each test finishes.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Line 18: testAdd() is the test function for add function. PHPUnit will recognize all functions&#13;
                        prefixed with test as a test function and run them automatically. This function is actually very&#13;
                        straightforward: we first call Calculator.add function to calculate the value of 1 plus 2. Then&#13;
                        we check to see if it returns the correct value by using PHPUnit function assertEquals.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The last part of the task is to run PHPUnit and make sure it passes all tests. Navigate to the&#13;
                    folder where you have created the test file and run the commands below from your terminal:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
vendor/bin/phpunit CalculatorTest.php&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    You should be able to see the successful message as below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
PHPUnit 5.0.9 by Sebastian Bergmann and contributors.&#13;
.                           1 / 1 (100%)&#13;
&#13;
Time: 40 ms, Memory: 2.50Mb&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Data Provider&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;When to use data provider&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    When we write a function, we want to make sure it passes a series of edge cases. The same applies to&#13;
                    tests. This means we will need to write multiple tests to test the same function using different&#13;
                    sets of data. For instance, if we want to test our Calculator class using different data, without&#13;
                    data provider, we would have multiple tests as shown below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
require 'Calculator.php';&#13;
class CalculatorTest extends PHPUnit_Framework_TestCase&#13;
{&#13;
    private $calculator;&#13;
&#13;
    protected function setUp()&#13;
    {&#13;
        $this-&gt;calculator = new Calculator();&#13;
    }&#13;
&#13;
    protected function tearDown()&#13;
    {&#13;
        $this-&gt;calculator = NULL;&#13;
    }&#13;
&#13;
    public function testAdd()&#13;
    {&#13;
        $result = $this-&gt;calculator-&gt;add(1, 2);&#13;
        $this-&gt;assertEquals(3, $result);&#13;
    }&#13;
&#13;
    public function testAddWithZero()&#13;
    {&#13;
        $result = $this-&gt;calculator-&gt;add(0, 0);&#13;
        $this-&gt;assertEquals(0, $result);&#13;
    }&#13;
&#13;
    public function testAddWithNegative()&#13;
    {&#13;
        $result = $this-&gt;calculator-&gt;add(-1, -1);&#13;
        $this-&gt;assertEquals(-2, $result);&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;In this case, we can use data provider function in PHPUnit to avoid duplication in our tests.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;How to use data provider&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A data provider method returns a variety of arrays or an object that implements the Iterator&#13;
                    interface. The test method will be called with the contents of the array as its arguments.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Some key points to keep in mind when using data provider are:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;Data provider method must be public.&lt;/li&gt;&#13;
                    &lt;li&gt;Data provider returns an array of a collection data.&lt;/li&gt;&#13;
                    &lt;li&gt;Test method use annotation(@dataProvider) declares its data provider method.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Once we know the key points, it is actually quite straightforward to use data provider. First, we create a new public method, which returns an array of a collection data as arguments of the test method.Then, we add annotation to the test method to tell PHPUnit which method will provide arguments.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Add data provider to our first unit test&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Let's modify our tests above using data provider.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
require 'Calculator.php';&#13;
class CalculatorTest extends PHPUnit_Framework_TestCase&#13;
{&#13;
    private $calculator;&#13;
&#13;
    protected function setUp()&#13;
    {&#13;
        $this-&gt;calculator = new Calculator();&#13;
    }&#13;
&#13;
    protected function tearDown()&#13;
    {&#13;
        $this-&gt;calculator = NULL;&#13;
    }&#13;
&#13;
    public function addDataProvider()&#13;
    {&#13;
        return array(&#13;
            array(1,2,3),&#13;
            array(0,0,0),&#13;
            array(-1,-1,-2),&#13;
        );&#13;
    }&#13;
&#13;
    /**&#13;
     * @dataProvider addDataProvider&#13;
     */&#13;
    public function testAdd($a, $b, $expected)&#13;
    {&#13;
        $result = $this-&gt;calculator-&gt;add($a, $b);&#13;
        $this-&gt;assertEquals($expected, $result);&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;Line 18: Add a data provider method. Take note that a data provider method must be declared as public.&lt;/li&gt;&#13;
                    &lt;li&gt;Line 27: Use annotation to declare the test method's data provider method.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now, run our test again and it should pass. As you can see, we have utilized data provider to avoid code duplication. Instead of writing three test methods for essentially the same method, we now have only one test method.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Test Double&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;When to use test double&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As mentioned in the first part of this series. One of PHPUnit's powerful features is test double. It is very common in our code that a method of a class calls another class's method. In this case, there is a dependency between these two classes. In particular, the caller class has a dependency on the calling class, but as we already know from part 1, unit test should test the smallest unit of functionality. In this case, it should test only the caller function. To solve this problem, we can use test double to replace the calling class. Since a test double can be configured to return predefined results, we can focus on testing the caller function.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Types of test doubles&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Test double is a generic term for objects we use, to replace real production ready objects. In our experience, it is very useful to categorize test doubles by their purpose. It not only makes it easy for us to understand the test case, but also make our code friendly to other parties.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Accordingly to Martin Fowler's post, there are five types of test double:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.&lt;/li&gt;&#13;
                    &lt;li&gt;Fake objects actually have working implementations, but usually take some shortcuts, which make them not suitable for production.&lt;/li&gt;&#13;
                    &lt;li&gt;Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test.&lt;/li&gt;&#13;
                    &lt;li&gt;Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent. Mocks are pre-programmed with expectations that form a specification of the calls they are expected to receive. They can throw an exception if they receive a call they don't expect and are checked during verification to ensure they received all the calls they were expecting.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;How to create test double&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    PHPUnit's method getMockBuilder can be used to create any similar user defined objects. Combining with its configurable interface, we can use it to create basically all five types of test doubles.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Add test double to our first unit test&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    It is meaningless to use test double in our calculator test case, since currently the Calculator class has no dependency on other classes, however, to demonstrate how to use test double in PHPUnit, we will create a stub Calculator class and test it.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's add a test case called testWithStub to our existing class:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
public function testWithStub()&#13;
{&#13;
    // Create a stub for the Calculator class.&#13;
    $calculator = $this-&gt;getMockBuilder('Calculator')&#13;
                       -&gt;getMock();&#13;
&#13;
    // Configure the stub.&#13;
    $calculator-&gt;expects($this-&gt;any())&#13;
               -&gt;method('add')&#13;
               -&gt;will($this-&gt;returnValue(6));&#13;
&#13;
    $this-&gt;assertEquals(6, $calculator-&gt;add(100,100));&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;getMockBuilder() method creates a stub similar to our Calculator object.&lt;/li&gt;&#13;
                    &lt;li&gt;getMock() method returns the object.&lt;/li&gt;&#13;
                    &lt;li&gt;expects() method tells the stub to be called any number of times.&lt;/li&gt;&#13;
                    &lt;li&gt;method() method specifies which method it will be called.&lt;/li&gt;&#13;
                    &lt;li&gt;will() method configures the return value of the stub.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We have introduced some basic usage of PHPUnit, which provides almost all the features we would need to create unit tests. You should always try to find more information from its official manual as you needed.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
&#13;
                &lt;h6 id="sec2"&gt;TDD by example&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In this section, we will demonstrate the process behind TDD through a very simple example. You should concentrate on how the three phases of TDD are carried out in this example.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Suppose we are given a task of building a price calculator for our e-commerce system. The class we are going to develop will be PriceCalculator. Let's first setup the project's folder and file structure as well as its dependencies.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
&#13;
                    As usual, we will use Composer as our package manager and PSR-4 as our code standard. The only third party dependency is PHPUnit. To set things up, we will create a folder src for placing our source files, and a folder tests for placing test files. We will also create src/PriceCalculator.php and tests/PriceCalculatorTest.php respectively. Finally, we will create a composer.json file as below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
{&#13;
    "require": {&#13;
        "phpunit/phpunit": "^5.0"&#13;
    },&#13;
    "autoload": {&#13;
        "psr-4": {&#13;
            "Dilab\\Order\\": "src"&#13;
        }&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This file tells Composer to download PHPUnit and tells autoloader that our source code follows PRS-4 standard.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    By running command composer install, we should end up with a folder structure as below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
.&#13;
+-- src&#13;
|   +-- PriceCalculator.php&#13;
+-- tests&#13;
|   +-- PriceCalculatorTest.php&#13;
+-- vendor&#13;
|   +-- dependency-1&#13;
|   +-- dependency-2&#13;
|   +-- dependency-3&#13;
|   +-- dependency-xxx&#13;
+-- composer.json&#13;
+-- composer.lock&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&#13;
                    The final piece we need for the setup is a phpunit.xml file to config PHPUnit. Let's create it as the folder root.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;&#13;
&amp;lt;phpunit backupGlobals="false"&#13;
         backupStaticAttributes="false"&#13;
         bootstrap="vendor/autoload.php"&#13;
         colors="true"&#13;
         convertErrorsToExceptions="true"&#13;
         convertNoticesToExceptions="true"&#13;
         convertWarningsToExceptions="true"&#13;
         processIsolation="false"&#13;
         stopOnFailure="false"&#13;
         syntaxCheck="false"&amp;lt;&#13;
    &amp;lt;testsuites&amp;gt;&#13;
        &amp;lt;testsuite name="Test Suite"&amp;gt;&#13;
            &amp;lt;directory suffix=".php"&amp;gt;./tests/&lt;/directory&amp;gt;&#13;
        &amp;lt;/testsuite&amp;gt;&#13;
    &amp;lt;/testsuites&amp;gt;&#13;
&amp;lt;/phpunit&amp;gt;&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Our final folder structure should be as shown below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
.&#13;
+-- src&#13;
|   +-- PriceCalculator.php&#13;
+-- tests&#13;
|   +-- PriceCalculatorTest.php&#13;
+-- vendor&#13;
|   +-- dependency-1&#13;
|   +-- dependency-2&#13;
|   +-- dependency-3&#13;
|   +-- dependency-xxx&#13;
+-- composer.json&#13;
+-- composer.lock&#13;
+-- phpunit.xml&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Red phase&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    At this phase we will plan how our API will look like and create failing test. In this example, the required API method is very simple. We just want a method that accepts an array as its parameter and calculate the total price. We will name this method total .&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's create some tests in tests/PriceCalculatorTest.php file before we write any source code.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
namespace Dilab\Order\Test;&#13;
use Dilab\Order\PriceCalculator;&#13;
&#13;
class PriceCalculatorTest extends \PHPUnit_Framework_TestCase&#13;
{&#13;
    private $PriceCalculator;&#13;
&#13;
    public function setUp()&#13;
    {&#13;
        parent::setUp();&#13;
        $this-&gt;PriceCalculator = new PriceCalculator();&#13;
    }&#13;
&#13;
    public function tearDown()&#13;
    {&#13;
        parent::tearDown();&#13;
        unset($this-&gt;PriceCalculator);&#13;
    }&#13;
&#13;
    /**&#13;
    * @test&#13;
    */&#13;
    public function object_can_created()&#13;
    {&#13;
        $priceCalculator = new PriceCalculator();&#13;
        $this-&gt;assertInstanceOf('Dilab\Order\PriceCalculator', $priceCalculator);&#13;
    }&#13;
&#13;
    /**&#13;
    * @test&#13;
    */&#13;
    public function should_sum_price()&#13;
    {&#13;
        $items = [&#13;
            ['price' =&gt; 100],&#13;
            ['price' =&gt; 200],&#13;
        ];&#13;
&#13;
        $result = $this-&gt;PriceCalculator-&gt;total($items);&#13;
        $this-&gt;assertEquals(300, $result);&#13;
    }&#13;
&#13;
    /**&#13;
    * @test&#13;
    */&#13;
    public function empty_items_should_return_zero()&#13;
    {&#13;
        $items = [];&#13;
        $result = $this-&gt;PriceCalculator-&gt;total($items);&#13;
        $this-&gt;assertEquals(0, $result);&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We have created three tests for PriceCalculator:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;public function object_can_created() : This test assures the object can be instantiated. Some may argue that this is unnecessary, but from a TDD point of view, we like to have such a simple test. When this test is passed, we can naturally move on to ones testing its real behaviour.&lt;/li&gt;&#13;
                    &lt;li&gt;public function should_sum_price() : This method tests whether total method does its job as described.&lt;/li&gt;&#13;
                    &lt;li&gt;public function empty_items_should_return_zero() : This method tests an edge case, where there is no item in the order. In such case, total method should return zero.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now if we run vendor/bin/phpunit from terminal, we should get error as expected as below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
Fatal error: Class 'Dilab\Order\PriceCalculator' not found in tests/PriceCalculatorTest.php&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Green phase&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The task of this phase is to make the failing tests above pass with the easiest but not necessarily the best code. The ultimate goal of this phase is the green message.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The implementation is fairly easy. All we need to do is to sum up the value with a foreach loop.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
namespace Dilab\Order;&#13;
class PriceCalculator&#13;
{&#13;
    public function total($items)&#13;
    {&#13;
        $total = 0;&#13;
        foreach ($items as $item) {&#13;
            $total += $item['price'];&#13;
        }&#13;
        return $total;&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now if we run vendor/bin/phpunit from terminal, we should get a green message as below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
PHPUnit 5.09 by Sebastian Bergmann and contributors.&#13;
&#13;
...             3 / 3 (100%)&#13;
&#13;
Time: 78 ms, Memory: 2.75Mb&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Refactoring phase&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This is the final phase of TDD, which we believe is the most valuable part of TDD. In this phase, we will take a look at the code we have written previously, and think of ways to make it cleaner and better.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We are using a foreach loop inside total method. It loops through $items array and returns the sum of the each individual element. This is actually a perfect use case of&#13;
                    array_reduce method. Function array_reduce iteratively reduces the array to a single value using a callback function. Let's refactor our code by replacing foreach loop with&#13;
                    array_reduce .&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
public function total($items)&#13;
{&#13;
    return array_reduce($items, function ($carry, $item) {&#13;
       return $carry + $item['price'];&#13;
    }, 0);&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If we run our tests again and they all still pass, we are good to go. Because we need to run the tests constantly to make sure refactoring does not break anything, it is important to keep our code fast.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We have cleaned up our code from five lines to two lines. There is no more temporary variable. The method has become easier to debug. There might not be apparent benefits for doing so in this example, but imagine this in a large scale project, even cleaning up one line of code could potentially make development easier.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This is the end of TDD. To emphasize again, the spirit of TDD is to let tests drive our development. Using PHPUnit in a project does not necessarily make it a TDD driven project. It is the three phases processes involved in the development that make it TDD.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec3"&gt;The end&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;&#13;
</description><pubDate>Mon, 05 Feb 2018 13:43:40 +0000</pubDate></item><item><title>Modern PHP Developer - Exception</title><link>https://www.startutorial.com/articles/view/modern-php-developer-exception</link><guid>https://www.startutorial.com/articles/view/modern-php-developer-exception<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Since PHP 5 was released, Exception is added to PHP as an object-oriented programming language&#13;
                    feature. By definition, an Exception is an exceptional event during program execution. In PHP, an&#13;
                    Exception is simply an object (an instance of Exception class). When an exception occurs, PHP will&#13;
                    halt current execution flow and look for an handler, and then it will continue its execution by the&#13;
                    handler's code. If no handler is found, a PHP Fatal Error will be issued with an "Uncaught Exception&#13;
                    ..." message and the program terminates.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;When to use Exception&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;How to use Exception&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Create your first custom exception 5.3&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;SPL exceptions&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec5"&gt;RuntimeException&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec6"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. When to use Exception&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Exception is good for handling exceptional cases of your program, however it is not the solution for&#13;
                    all error cases. Sometimes it is perfectly fine to return a boolean FALSE. Sometimes you are much&#13;
                    better off throwing exceptions instead of returning weird error codes. Therefore it is very&#13;
                    important to understand when to use Exception and when not to.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    By now, we all know an exception should be thrown when an exceptional situations occurs. But if&#13;
                    exceptional situation seems rather arbitrary, what qualifies as an "exceptional" situation?&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Here is a good rule of thumb: since exceptional situations don't happen frequently, if you supply&#13;
                    correct values to your function and remove the thrown exception, if the function then fails, the&#13;
                    exception is used incorrectly.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's take a look at some concrete examples:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;If you create a function to save a user's input to database, when a database connection fails,&#13;
                        an exception should be thrown.&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        For the same function, you create a validator for checking a user's input. When an invalid value&#13;
                        is supplied, you should not throw an exception. Invalid value is a rather frequent case for a&#13;
                        validator class.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;A good use case of Exception&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Here we have an example of returning error codes to indicate error cases:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class User {&#13;
    ...&#13;
    public function login()&#13;
    {&#13;
        if ($this-&gt;invalidUsernameOrPassword()) {&#13;
            return -2;&#13;
        }&#13;
        if ($this-&gt;tooManyLoginAttempts()) {&#13;
            return -1;&#13;
        }&#13;
        return 1;&#13;
    }&#13;
&#13;
    public function redirectToUserPage()&#13;
    {&#13;
        ...&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Client code might be something similar to the below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$user = new User();&#13;
$result = $user-&gt;login();&#13;
if (-2 == $result) {&#13;
    log('invalid username or password');&#13;
} else if (-1 == $result) {&#13;
    log('too many login attempts');&#13;
} else if (1 == $result) {&#13;
    $user-&gt;redirectToUserPage();&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Here we can spot a couple of problems with error codes:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;Error codes do not contain error related information by themselves, which make them very hard to&#13;
                        maintain.&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;Error codes result in number of if/else statements in client's code, depending on how many there&#13;
                        are. (Conditional statements should be eliminated as much as possible, in order to make our code&#13;
                        clean).&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's refactor the code to use exceptions:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class User {&#13;
    ...&#13;
&#13;
    public function login()&#13;
    {&#13;
        if ($this-&gt;invalidUsernameOrPassword()) {&#13;
            throw new InvalidCredentialException('Invalid username or password');&#13;
        }&#13;
&#13;
        if ($this-&gt;tooManyLoginAttempts()) {&#13;
            throw new LoginAttemptsException('Too many login attempts');&#13;
        }&#13;
    }&#13;
&#13;
    public function redirectToUserPage()&#13;
    {&#13;
        ...&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    And client code can be refactored as:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
try {&#13;
    $user = new User();&#13;
    $user-&gt;login();&#13;
    $user-&gt;redirectToUserPage();&#13;
} catch (InvalidCredentialException $e) {&#13;
    log($e-&gt;getMessage());&#13;
} catch (LoginAttemptsException $e) {&#13;
    log($e-&gt;getMessage());&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As we can see, by using exceptions, the second code sample conveys messages about the errors much&#13;
                    more clearly. Beyond that, in the client code, by eliminating conditional statements, the code&#13;
                    become self-explanatory.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;&#13;
                        A case of misusing Exception&#13;
                    &lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    One common way of misusing exceptions is using them to control the flow of application logic. It is&#13;
                    not only confusing, but also slows down your code. To emphasize again, exception is used to raise&#13;
                    exceptional situations.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Below is one example of of misusing exceptions, which is discouraged.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
function register($email, $role) {&#13;
    try {&#13;
        if ($role == 'member') {&#13;
            throw new CreateMemberException();&#13;
        } else if ($role == 'admin') {&#13;
            throw new CreateAdminException();&#13;
        }&#13;
    } catch (CreateMemberException $e) {&#13;
        // code for creating member account&#13;
    } catch (CreateAdminException $e) {&#13;
        // code for creating admin account&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The function register() uses exceptions to delegate account creation tasks. This is obviously&#13;
                    against rules of exceptions. Though PHP does not stop you, you should religiously forbid yourself&#13;
                    from doing this.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. How to use Exception&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Four key words are associated with Exception. They are: throw , try , catch and finally . An&#13;
                    exception object is thrown( throw ) in a method when an exceptional event happens. Clients that call&#13;
                    the method will normally place the method in a try block and&#13;
                    catch it with some handling code. A finally block ensures the code inside the block will always be&#13;
                    executed.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Throw&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    All exceptions in PHP are a class or subclass of Exception. It takes three optional parameters in&#13;
                    its constructor.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL)&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&#13;
                        $message: The exception message. This message provides some human readable information. And&#13;
                        normally supply this parameter when instantiating an exception.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        $code: It is useful for identifying types of exceptions that belong to the same class.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        $previous: The exception before current one. This is normally used when we want to re- throw an exception in a catch block.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Below is an example of PHP syntax to throw an exception&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
 throw new Exception('some error message');&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The keyword here is throw . Note that we first need to initiate an exception object.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;&#13;
                        Catch&#13;
                    &lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    When we need to catch exceptions, we place the callee in a try-catch block as below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
try {&#13;
    methodThatThrowsExceptions();&#13;
} catch (Exception $e) {&#13;
    // handle exception gracefully&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The catch block is where we place our handler code. Detailed exception handling implementation varies depending on application design. For example, we could try to recover the exception as much as we can, and if that is not possible, we could redirect users to a customer support page. If we leave it unhanded, PHP will eventually terminate the program and leave users with a page of meaningless error message, which is discouraged.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;Exception bubble effect&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you are using some kind of frameworks, exceptions are likely handled even if you never actually create any handler for them. That is because exceptions bubble up, and your framework will eventually handle them. A simple example of exception bubble effect is:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
function methodA()&#13;
{&#13;
    throw new Exception('error from methodA');&#13;
}&#13;
&#13;
function methodB()&#13;
{&#13;
    methodA();&#13;
}&#13;
&#13;
function methodC()&#13;
{&#13;
    try {&#13;
        methodB();&#13;
    } catch (Exception $e) {&#13;
        // handle error gracefully&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In the sample code, when methodC is called, it calls methodB, which directly invokes methodA. An exception is thrown in methodA, since methodB does not handle it. It then bubbles up to methodC, which gracefully handles the exception. In this example, though methodC does not call methodA directly, because exception bubbles up the stack, it is still handled gracefully at the end.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Multiple catch blocks&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A method might contain different exceptions: some might be directly thrown by themselves and some might be bubbled up from their underlying stack. The catch block is designed to handle multiple exceptions, so we can have multiple catch blocks for handling different exceptions. A caveat here is that the position matters.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In multiple catch blocks, PHP picks the first block that matches the thrown exception's type. A good rule for positioning catch blocks is from a more specific one to a less specific one.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's see it in an example.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class ExceptionA extends Exception{}&#13;
&#13;
class ExceptionB extends ExceptionA{}&#13;
&#13;
try {&#13;
    methodThatThrowsExceptionA();&#13;
&#13;
} catch (ExceptionA $e) {&#13;
&#13;
} catch (ExceptionB $e) {&#13;
&#13;
} catch (Exception $e) {&#13;
&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In the sample code, it is obvious ExceptionA catch block will get picked. Now let's change the method to throw ExceptionB.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class ExceptionA extends Exception{}&#13;
&#13;
class ExceptionB extends ExceptionA{}&#13;
&#13;
try {&#13;
&#13;
    methodThatThrowsExceptionB();&#13;
&#13;
} catch (ExceptionA $e) {&#13;
&#13;
} catch (ExceptionB $e) {&#13;
&#13;
} catch (Exception $e) {&#13;
&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Which catch block do you think it will be picked? The answer is still ExceptionA. Because ExceptionA is a parent class of ExceptionB, when ExceptionB is thrown, ExceptionA catch block comes first and matches the thrown exception's type, giving ExceptionB is an instance of ExceptionA.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This can be fixed by positioning them from the the more specific type to a less specific type, as shown below:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class ExceptionA extends Exception{}&#13;
&#13;
class ExceptionB extends ExceptionA{}&#13;
&#13;
try {&#13;
&#13;
    methodThatThrowsExceptionB();&#13;
&#13;
} catch (ExceptionB $e) {&#13;
&#13;
} catch (ExceptionA $e) {&#13;
&#13;
} catch (Exception $e) {&#13;
&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;trace message&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Since exceptions can be thrown anywhere in your program, it is very important to find the root cause. Exception provides various APIs to make it easy to trace where the exception comes from.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Seven public methods are extracted from PHP manual file:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;final public string getMessage ( void )&lt;/li&gt;&#13;
                    &lt;li&gt;final public Exception getPrevious ( void )&lt;/li&gt;&#13;
                    &lt;li&gt;final public mixed getCode ( void )&lt;/li&gt;&#13;
                    &lt;li&gt;final public string getFile ( void )&lt;/li&gt;&#13;
                    &lt;li&gt;final public int getLine ( void )&lt;/li&gt;&#13;
                    &lt;li&gt;final public array getTrace ( void )&lt;/li&gt;&#13;
                    &lt;li&gt;final public string getTraceAsString ( void )&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    And we can use them to trace details of the thrown exception:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;Exception::getMessage — Gets the Exception message&lt;/li&gt;&#13;
                    &lt;li&gt;Exception::getPrevious — Returns previous&lt;/li&gt;&#13;
                    &lt;li&gt;Exception Exception::getCode — Gets the Exception code&lt;/li&gt;&#13;
                    &lt;li&gt;Exception::getFile — Gets the file in which the exception occurred&lt;/li&gt;&#13;
                    &lt;li&gt;Exception::getLine — Gets the line in which the exception occurred&lt;/li&gt;&#13;
                    &lt;li&gt;Exception::getTrace — Gets the stack trace&lt;/li&gt;&#13;
                    &lt;li&gt;Exception::getTraceAsString — Gets the stack trace as a string&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;Let's put it in action.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    For demonstration purpose, let's pretend we have a createAccount() method, which throws an Exception when an email address is invalid.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
function createAccount($email)&#13;
{&#13;
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {&#13;
        throw new Exception('In valid email address');&#13;
    }&#13;
&#13;
    return sprintf('account creation email is sent to %s', $email);&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    What information can we get if we trigger the exception?&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
function linSeparator()&#13;
{&#13;
    return PHP_EOL.'----------------------------------'.PHP_EOL;&#13;
}&#13;
&#13;
try {&#13;
&#13;
    createAccount('test');&#13;
&#13;
} catch (Exception $e) {&#13;
    echo $e-&gt;getMessage();&#13;
    echo linSeparator();&#13;
&#13;
    echo $e-&gt;getPrevious();&#13;
    echo linSeparator();&#13;
&#13;
    echo $e-&gt;getCode();&#13;
    echo linSeparator();&#13;
&#13;
    echo $e-&gt;getFile();&#13;
    echo linSeparator();&#13;
&#13;
    print_r($e-&gt;getTrace());&#13;
    echo linSeparator();&#13;
    echo $e-&gt;getTraceAsString();&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&#13;
                    Running the script from CLI, we get the following:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
In valid email address&#13;
----------------------------------&#13;
&#13;
----------------------------------&#13;
0&#13;
----------------------------------&#13;
/Users/xu/Desktop/Exception/trace.php&#13;
&#13;
----------------------------------&#13;
Array&#13;
(&#13;
    [0] =&gt; Array (&#13;
        [file] =&gt; /Users/xu/Desktop/Exception/trace.php&#13;
        [line] =&gt; 19&#13;
        [function] =&gt; createAccount&#13;
        [args] =&gt; Array&#13;
        (&#13;
            [0] =&gt; test&#13;
        )&#13;
    )&#13;
)&#13;
&#13;
----------------------------------&#13;
#0 /Users/xu/Desktop/Exception/trace.php(19): createAccount('test')&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Beside obvious trace information, we can also tell that, the default code is 0 and previous exception is null when instantiating an exception object.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
public __construct (string $message = "" , int $code = 0 , Exception $previous = NULL);&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    One more point we want to address here is that an exception is created when it is instantiated, not when it is thrown. So Exception APIs will give you information related to the time an exception is instantiated.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    For example, in the method below, Exception::getLine will return 2.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
function methodThrowException()&#13;
{&#13;
    $exception = new Exception('error from methodThrowException'); // line 2&#13;
    throw $exception; // line 3&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;finally&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Before PHP 5.5, there was not finally block in PHP. A problem surfaced. If we wanted to ensure that one piece of code always ran regardless of which catch block got picked, we had to put that piece of code into each one of catch blocks.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    To solve this problem, finally block was introduced since PHP 5.5. Code inside finally block will always be executed after catch block. We can even use try/catch only without catch .&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This block is a place for us to do some clean up jobs. Tasks such as rolling back database transactions, closing database connections, releasing file locks and so on. Its usage is pretty straightforward.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    For example, to use it alongside try/catch blocks:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
try {&#13;
    createAccount('test');&#13;
} catch (Exception $e) {&#13;
    echo $e-&gt;getMessage();&#13;
} finally {&#13;
    echo 'Close Database Connection';&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Use try/finally block only:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
try {&#13;
    createAccount('test');&#13;
} finally {&#13;
    echo 'Close Database Connection';&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. Create your first custom exception&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Throwing custom exception allows client code to handle the error case in a recognized manner. For example, when a database exception is thrown, it is reasonable to shut down the process completed. However, in the case of an invalid user input, we might just want to log an error message.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    By creating custom exceptions, we express error cases of our code proactively. This not only helps the clients to avoid pitfalls, but also gives them enough information to handle the error cases confidently.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As all exceptions in PHP 5.x use Exception as the base, we are actually extending Exception to create our custom exception. In this example, let's revisit our previous code.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class User {&#13;
    ...&#13;
&#13;
    public function login()&#13;
    {&#13;
        if ($this-&gt;invalidUsernameOrPassword()) {&#13;
            throw new InvalidCredentialException('Invalid username or password');&#13;
        }&#13;
        if ($this-&gt;tooManyLoginAttempts()) {&#13;
            throw new LoginAttemptsException('Too many login attempts');&#13;
        }&#13;
    }&#13;
&#13;
    public function redirectToUserPage()&#13;
    {&#13;
    ...&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We have two custom exceptions here (InvalidCredentialException and LoginAttemptsException). They should actually be under one type. And they will be assign different messages.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Since InvalidCredentialException and LoginAttemptsException are error cases for an invalid login runtime error, it is reasonable to create an exception called InvalidLoginException, and use it for the two error cases above.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    It is simple enough to create a custom exception with only one line of code.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class InvalidLoginException extends Exception {}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We can refactor previous code to use the newly created exception class:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class User {&#13;
    ...&#13;
    public function login()&#13;
    {&#13;
        if ($this-&gt;invalidUsernameOrPassword()) {&#13;
            throw new InvalidLoginException('Invalid username or password');&#13;
        }&#13;
&#13;
        if ($this-&gt;tooManyLoginAttempts()) {&#13;
            throw new InvalidLoginException('Too many login attempts');&#13;
        }&#13;
    }&#13;
&#13;
    public function redirectToUserPage()&#13;
    {&#13;
    ...&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;A little trick&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A potential issue might appear shortly, if we are using InvalidLoginException with too many different messages. The issue is easy to illustrate.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Imagine somewhere in our code, we need to throw another InvalidLoginException when an user account is blocked. We will throw the exact InvalidLoginException, but with different messages. The same thing happens again, and we will repeat the same actions. The list adds up. Now imagine doing this for different types of exceptions. We would lose track as the developer.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    So here is a little trick: we shift the exception creation task to InvalidLoginException class.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class InvalidLoginException extends Exception&#13;
{&#13;
    public static function invalidUsernameOrPassword() {&#13;
        return new static('Invalid username or password');&#13;
    }&#13;
&#13;
    public static function tooManyLoginAttempts() {&#13;
        return new static('Too many login attempts');&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Now the client code becomes:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&#13;
class User {&#13;
    ...&#13;
    public function login()&#13;
    {&#13;
        if ($this-&gt;invalidUsernameOrPassword()) {&#13;
            throw InvalidLoginException::invalidUsernameOrPassword();&#13;
        }&#13;
&#13;
        if ($this-&gt;tooManyLoginAttempts()) {&#13;
            throw InvalidLoginException::tooManyLoginAttempts();&#13;
        }&#13;
    }&#13;
&#13;
    public function redirectToUserPage()&#13;
    {&#13;
    ...&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    When the instantiation of exception is shifted to a function block, we gain much more space and freedom to do more interesting stuff, compared to a single line within the if block previously.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    By keeping all of them in a centralized location, which is the exception class itself, not only does it create a more maintainable code base, but also give clients an opportunity to take a quick glance what exact exception they would expect.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. SPL exceptions&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Creating your own custom exception is great, but it does take some mental energy to come out as a meaningful name. Naming is hard, arguably one of the hardest thing in programming.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The Standard PHP Library (SPL) provides a set of standard Exceptions. We should use them for our own benefit. They cover a list of common error cases, which can save us energy if we were to come out on our own. Additionally, we can also expand from these standard Exceptions to make them more specific to our own domain.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In this sections, we will go through 14 SPL Exceptions, explaining them in simplest terms, so that you can use them next time in your own project.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
-LogicException (extends Exception)&#13;
    --BadFunctionCallException&#13;
    --BadMethodCallException&#13;
    --DomainException&#13;
    --InvalidArgumentException&#13;
    --LengthException&#13;
    --OutOfRangeException&#13;
-RuntimeException (extends Exception)&#13;
    --OutOfBoundsException&#13;
    --OverflowException&#13;
    --RangeException&#13;
    --UnderflowException&#13;
    --UnexpectedValueException&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    There are two main categories of SPL Exceptions. They are LogicException and RuntimeException, Under each one of them, there are a few sub exception classes describing more specific error cases.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Logic Errors&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;LogicExcetpion&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    It's not hard to tell from its name that, LogicException covers error cases related to logics. As it is a parent class for a few more specific exceptions, it is a bit generic. When your code is returning or receiving something that is not logic, there is a logic error. When an error case is determined to be a logic error, use LogicException if you cannot find a better fit from its subclasses.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;BadFunctionCallException&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    When an non-existing function get called, or wrong parameters are supplied to a function, this exception gets thrown. As this exception covers function scope, not method in a class, it is mostly thrown by PHP.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;BadMethodCallException&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    When an non-existing method of a class gets called, or wrong parameters are supplied to that method, an BadFunctionCallException can be thrown. While this exception is similar to to BadFunctionCallException, it is designed for class scope.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;DomainException&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Domain here refers to the business our code works for. When a parameter is valid by its datatype, but invalid to the domain, a DomainException can be thrown.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    For example, in an universal image manipulation function, transformImage($imageType) , DomainException should be thrown when $imageType contains an invalid image type. To this domain, an invalid image type is a domain error.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;InvalidArgumentException&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;p&gt;This one is simple, as its name says: it should be thrown when an invalid argument is supplied.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    PHP5 introduces type hinting, however it does not yet work for scalar types such as int, string yet. To make it work, we throw InvalidArgumentException when a scalar type does not meet the requirement.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;LengthException&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We can use this exception when length of something is invalid. For example, password needs to be at least 8 characters.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;OutOfRangeException&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Use this exception when an invalid index is accessed. The keyword here is range.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
&#13;
                &lt;h6 id="sec5"&gt;5. RuntimeException&lt;/h6&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&#13;
                    RuntimeException is a name derived from compile language, such as Java. In Java, there are two main categories of exception: checked exceptions and runtime exceptions. A complier won't compile the code until all checked exception are handled (in a catch block). Runtime exception can only be detected at run time and is not required to place these exceptions in a catch block.&#13;
&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Since PHP is not a compile language, we can think of its "compile time" as the time we write the code, and its "run time" as the code execution time. "Compile time" exceptions can be detected in development time, for example invalid datatype parameter.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    To avoid confusion, keep in mind that logic exceptions discussed above are for "compile time".&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    RuntimeException's subclasses cover more specific scenarios. Use this exception if you cannot find a better fit from its subclasses.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;OutOfBoundsException&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This exception is used when an invalid index is called. Not to be confused with OutOfRangeException, OutOfBoundsException is a run time exception.&#13;
&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    For example, when a user creates an array data structure and when an invalid index is called, an OutOfBoundsException should be thrown. Whereas trying to obtain the day of week using 8 should throw an OutOfRangeException.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$booksList = array();&#13;
&#13;
$bookList[5];     // OutOfBoundsException&#13;
&#13;
$dayOfWeek = $calendar-&gt;day(8); // OutOfRangeException&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;OverflowException&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    When a container with limited capacity is asked to fill more than it can hold, this exception can be thrown.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;RangeException&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This exception is for generic error cases related to range at "run time".&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;UnderflowException&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Opposite of OverflowException is UnderflowException. When an empty container is asked to remove an element, this exception can be thrown.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;UnexpectedValueException&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As simple as its name says, when an unexpected value is raised or accessed, we throw this exception.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    That is all the exceptions provided by PHP SPL. We should always throw the most accurate exception for an error case. Inevitably, one exception may fit under multiple exceptions in which case, it is fine to pick one.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    An meaningful exception message goes a long way towards a maintainable project.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec6"&gt;6. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    Did we miss out anything? Do leave a comment below to let us know.&#13;
                &lt;/p&gt;&#13;
&#13;
</description><pubDate>Mon, 05 Feb 2018 13:42:42 +0000</pubDate></item><item><title>Modern PHP Developer - Iterator</title><link>https://www.startutorial.com/articles/view/modern-php-developer-iterator</link><guid>https://www.startutorial.com/articles/view/modern-php-developer-iterator<isPermaLink>true</isPermaLink></guid><description>                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Your first iterator class&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Why iterator?&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;SPL Iterators&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;ArrayObject vs SPL ArrayIterator&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec5"&gt;Iterating the File System&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec6"&gt;Peeking ahead with CachingIterator&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec7"&gt;Generator&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec8"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&#13;
                    If you have used a for loop in PHP, the idea of iteration is most likely not foreign to you. You pass an array to a for loop, and perform some logic inside the loop, but did you know that you can actually pass data structures other than arrays to a for loop? That's where Iterator comes into play.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Below is summarised definition of an iterator from Wikipedia:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;blockquote&gt;&#13;
                    In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists.[...] Note that an iterator performs traversal and also gives access to data elements in a container, but does not perform iteration [...]. An iterator is behaviorally similar to a database cursor.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Some key points to remember here:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;Iterator enables us to traverse a container. It is similar to arrays.&lt;/li&gt;&#13;
                    &lt;li&gt;Iterator does not perform iteration. In our previous example, for does the iteration. Other loop types such as foreach and while do iteration.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now that we know the definition of Iterator, the concept may still be somewhat obscure, but do not worry, we aren't done yet. We have now established that Iterator works similar to array and it can be loop through in a for loop.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    It is helpful to understand how array actually works in a for loop. Let's take a look at the code below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$data = array(1,2,3,4);&#13;
for ($i=0; $i&lt;count($data); $i++) {&#13;
    $key = $i;&#13;
    $value = $data[$i];&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Here is how an array works in a for loop:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&#13;
                        In step 1, we set $i to 0.( $i=0 )&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        In step 2, we check to see $i is less than the length of $data. ( $i&lt;count($data) )&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        In step 3, we increase $i value by 1. ( $i++ )&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        In step 4, we can access the key of the current element. ( $key = $i )&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        In step 5, we can also get the value of current element. ( $value = $data[$i] )&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We can abstract the steps as simple functions as below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;Step 1 = rewind().&lt;/li&gt;&#13;
                    &lt;li&gt;Step 2 = valid().&lt;/li&gt;&#13;
                    &lt;li&gt;Step 3 = next().&lt;/li&gt;&#13;
                    &lt;li&gt;Step 4 = key().&lt;/li&gt;&#13;
                    &lt;li&gt;Step 5 = current().&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In abstract level, we can imagine that, as long as an object provides the five functions above, it can be loop through by a for loop.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In fact, an iterator is nothing but a class implements all five steps mentioned above. In PHP, The Standard PHP Library(SPL), which is a collection of interfaces and classes that are meant to solve common problems, provides a standard Iterator interface.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
Iterator extends Traversable {&#13;
    /* Methods */&#13;
    abstract public mixed current ( void )&#13;
    abstract public scalar key ( void )&#13;
    abstract public void next ( void )&#13;
    abstract public void rewind ( void )&#13;
    abstract public boolean valid ( void )&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Your first iterator class&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now that we understand what an iterator is, it's time to build our first one.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Our first iterator represents top 10 stared PHP repositories from Github. We can pass it into a foreach and loop through it just like an array. We will name it TrendingRepositoriesIterator.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    First, we need to make our class implement the Iterator interface.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class TrendingRepositoriesIterator implements Iterator&#13;
{&#13;
    public function rewind()&#13;
    {&#13;
    }&#13;
&#13;
    public function valid()&#13;
    {&#13;
    }&#13;
&#13;
    public function next()&#13;
    {&#13;
    }&#13;
&#13;
    public function key()&#13;
    {&#13;
    }&#13;
&#13;
    public function current()&#13;
    {&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    An iterator must always implement the five methods described above. Final code of TrendingRepositoriesIterator is as follow:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class TrendingRepositoriesIterator implements Iterator&#13;
{&#13;
    private $repos = [];&#13;
    private $pointer = 0;&#13;
    public function __construct()&#13;
    {&#13;
        $this-&gt;populate();&#13;
    }&#13;
    public function rewind()&#13;
    {&#13;
        $this-&gt;pointer = 0;&#13;
    }&#13;
    public function valid()&#13;
    {&#13;
        return isset($this-&gt;repos[$this-&gt;pointer]);&#13;
    }&#13;
    public function next()&#13;
    {&#13;
        $this-&gt;pointer++;&#13;
    }&#13;
    public function key()&#13;
    {&#13;
        return $this-&gt;pointer;&#13;
    }&#13;
    public function current()&#13;
    {&#13;
        return $this-&gt;repos[$this-&gt;pointer];&#13;
    }&#13;
    private function populate()&#13;
    {&#13;
        $client = new GuzzleHttp\Client();&#13;
        $res = $client-&gt;request('GET', 'https://api.github.com/search/repositories', [ 'query' =&gt; ['q' =&gt; 'language:php', 'sort' =&gt; 'stars', 'order' =&gt; 'desc']]);&#13;
        $resInArray = json_decode($res-&gt;getBody(), true);&#13;
        $trendingRepos = array_slice($resInArray['items'], 0, 10);&#13;
        foreach ($trendingRepos as $rep) {&#13;
            $this-&gt;repos[] = $rep['name'];&#13;
        }&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&#13;
                        public function populate(): We will not go in-depth regarding this function as that will defeat the purpose of this chapter. Basically this function fetches top 10 stared PHP repositories from Github via Github public API and store them into $repos property.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        private $repos: We use this property to store fetched repositories.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        private $pointer: We can use array's internal pointer to do the job, however since we are building our own iterator, we want to retain full control.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        public function __construct(): The property fetches target repositories when an object is instantiated.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        public function rewind(): We can use this to set pointer to first position.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        public function valid(): As long as the value of current pointer is set, it is valid.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        public function next(): This is used to increase the pointer by 1 position.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        public function current(): We can return value of current pointer through this function.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's see the use case of TrendingRepositoriesIterator, which can used just like an array:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$trendingRepositoriesIterator = new TrendingRepositoriesIterator();&#13;
&#13;
foreach ($trendingRepositoriesIterator as $repository) {&#13;
    echo $repository . "\n";&#13;
}&#13;
&#13;
// Output&#13;
laravel&#13;
symfony&#13;
CodeIgniter&#13;
DesignPatternsPHP&#13;
Faker&#13;
yii2&#13;
composer&#13;
WordPress&#13;
sage&#13;
cakephp&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Awesome! Now we have written our first iterator and as you can see, it is actually very easy and straightforward.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Why iterator?&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    You might still wonder why we need to use iterator. Can't we just use array? The answer is yes and no. In most cases, array is sufficient for the job, although iterator does come with some key advantages, which we will share next. Keep in mind, we are by no means suggesting using iterator in all circumstance.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;Encapsulation&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In our first iterator, TrendingRepositoriesIterator, the details of traversing Github repositories is completed hidden from outside. We can update how we get the data, where we get the data from, and how we want to traverse the resources. No change is needed from the client code. This, known as Encapsulation, is one of the key concepts of Object- Oriented Programming.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Additional examples include:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    To iterate through MySQl results, we can use:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$result = mysql_query("SELECT * FROM books");&#13;
&#13;
// Iterate over the structure&#13;
while ( $row = mysql_fetch_array($result) ) {&#13;
    // do stuff&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    To iterator through content of a text file, we can:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$fh = fopen("books.txt", "r");&#13;
// Iterate over the structure&#13;
while (!feof($fh)) {&#13;
   $line = fgets($fh);&#13;
   // do stuff with the line here&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    With iterator, we can encapsulate the process of traversing the recourse so that the outside world is not aware of the internal operations. In fact, the outside world does not need to know where we get the data from or how it is traversed in a loop. All they need to know is that, they can iterate through it as simply as:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$bookIterator = new BookIterator();&#13;
foreach($bookIterator as $book) {&#13;
    // do stuff with $book&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Encapsulation is a very powerful concept and it enables us to write clean code.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Efficient memory usage&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Efficient memory usage is a key benefit of iterator.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In our TrendingRepositoriesIterator class, we can actually fetch resource dynamically, meaning we will only fetch data from Github API when the next() method is called. This technique is called Lazy Loading. It helps us save a very significant amount of memory as value is only generated when it is needed.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;Easy to add additional functionalities&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Another benefit of using iterator is that we can decorate it to add additional functionalities. Take our TrendingRepositoriesIterator class for example. We want to exclude "laravel" from the resource. One obvious method is to update our original class, although that is of course not what we would do here.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We can decorate the original iterator using SPL's CallbackFilterIterator and no change is needed for TrendingRepositoriesIterator at all.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$trendingRepositoriesIterator = new TrendingRepositoriesIterator();&#13;
    return $value != 'laravel';&#13;
});&#13;
foreach ($newTrendingRepositoriesIterator as $repository) {&#13;
    echo $repository . "\n";&#13;
}&#13;
// Output&#13;
symfony&#13;
CodeIgniter&#13;
DesignPatternsPHP&#13;
Faker&#13;
yii2&#13;
composer&#13;
WordPress&#13;
sage&#13;
cakephp&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The cool part of this is that there is no duplication of objects. The callback fires only when TrendingRepositoriesIterator hits the next() method, and then the logic it will be applied accordingly. This is a great way to save memory as well as boost performance.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. SPL Iterators&lt;/h6&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&#13;
                    Now that we understand the power and benefits of using iterators, it is good practice to use iterators to solve suitable problems. However if we were to write iterators by ourselves whenever we encounter a new problem, it would be very time consuming since it does require us to implement a set of pre-defined functions.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Luckily PHP has done a good job of providing a set of iterators for solving some common problems. In the following sections, we will work through a set of common iterators provided by SPL. As a refresher, SPL standards for Standard PHP Library was built to provide a collection of interfaces and classes that are meant to solve common problems.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. ArrayObject vs SPL ArrayIterator&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In PHP, array is one of the eight primitive types. PHP provides 79 functions for handling array related tasks (reference). It is completely suitable to use array, however there are times, depending on how much you embrace Object-Oriented programming, that you may want to use array as an object. In this case, PHP provides two classes to make array a first class citizen in Object-Oriented code.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;ArrayObject&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The first option we have is ArrayObject. This class allows objects to work as arrays.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's take a look at its class signature:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
ArrayObject implements IteratorAggregate , ArrayAccess , Serializable , Countable{&#13;
 ...&#13;
 public ArrayIterator getIterator ( void )&#13;
 ...&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As we have seen above, ArrayObject implements IteratorAggregate. What is IteratorAggregate? It is an interface to create an external iterator. In simple terms, it is a quick way to create an iterator, instead of implementing Iterator interfaces with five methods: rewind,valid,current,key and valu, IteratorAggregate allows you to delegate that task to another iterator. All you need to do is implement a single method getIterator().&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
IteratorAggregate extends Traversable {&#13;
    abstract public Traversable getIterator ( void )&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    ArrayObject implements IteratorAggregate. It creates an external ArrayIterator for iterator feature.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As ArrayObject implements IteratorAggregate, we can use it in a foreach loop just as an array.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = array(&#13;
    'Head First Design Patterns',&#13;
    'Clean Code: A Handbook of Agile Software Craftsmanship',&#13;
    'Domain-Driven Design: Tackling Complexity in the Heart of Software',&#13;
    'Agile Software Development, Principles, Patterns, and Practices',&#13;
);&#13;
&#13;
$booksAsArrayObject = new ArrayObject($books);&#13;
&#13;
foreach ($booksAsArrayObject as $book) {&#13;
    echo $book . "\n";&#13;
}&#13;
&#13;
// Output&#13;
Head First Design Patterns&#13;
Clean Code: A Handbook of Agile Software Craftsmanship&#13;
Domain-Driven Design: Tackling Complexity in the Heart of Software&#13;
Agile Software Development, Principles, Patterns, and Practices&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The primary reason we want to use ArrayObject is to use array in Object-Oriented fashion.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = array(&#13;
    'Head First Design Patterns',&#13;
    'Clean Code: A Handbook of Agile Software Craftsmanship',&#13;
    'Domain-Driven Design: Tackling Complexity in the Heart of Software',&#13;
    'Agile Software Development, Principles, Patterns, and Practices',&#13;
);&#13;
&#13;
$booksAsArrayObject-&gt;append('The Pragmatic Programmer: From Journeyman to Master'); // --- vs ---&#13;
$books[] = 'The Pragmatic Programmer: From Journeyman to Master';&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;ArrayIterator&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    ArrayIterator works similar to ArrayObject.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's take look at its class signature as well:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
ArrayIterator implements ArrayAccess , SeekableIterator , Countable , Serializable {&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    It is almost identical to ArrayObject in terms of interfaces they implement. The only difference is, instead of ArrayIterator interface ArrayObject implements, it implements SeekableIterator.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We use ArrayIterator the same way as we use ArrayObject in a foreach loop:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = array(&#13;
    'Head First Design Patterns',&#13;
    'Clean Code: A Handbook of Agile Software Craftsmanship',&#13;
    'Domain-Driven Design: Tackling Complexity in the Heart of Software',&#13;
    'Agile Software Development, Principles, Patterns, and Practices',&#13;
);&#13;
$booksAsArrayIterator = new ArrayIterator($books);&#13;
foreach ($booksAsArrayIterator as $book) {&#13;
    echo $book . "\n";&#13;
}&#13;
// Output&#13;
Head First Design Patterns&#13;
Clean Code: A Handbook of Agile Software Craftsmanship&#13;
Domain-Driven Design: Tackling Complexity in the Heart of Software&#13;
Agile Software Development, Principles, Patterns, and Practices&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Use array in Object-Oriented fashion:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = array(&#13;
    'Head First Design Patterns',&#13;
    'Clean Code: A Handbook of Agile Software Craftsmanship',&#13;
    'Domain-Driven Design: Tackling Complexity in the Heart of Software',&#13;
    'Agile Software Development, Principles, Patterns, and Practices',&#13;
);&#13;
$booksAsArrayIterator = new ArrayIterator($books);&#13;
$booksAsArrayIterator-&gt;append('The Pragmatic Programmer: From Journeyman to Master'); // --- vs ---&#13;
$books[] = 'The Pragmatic Programmer: From Journeyman to Master';&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Comparison&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    You may be wondering when to use ArrayObject and when to use ArrayIterator. It is important to know the difference and the relationship between ArrayObject and ArrayIterator.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As we have already discovered in the ArrayObject section, ArrayObject actually creates ArrayIterator as an external iterator. It is fair to say ArrayIterator does what ArrayObject does, and it provides more functionality, specifically seeking to a position. This is accomplished by implementing SeekableIterator.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Besides moving a pointer from top to bottom as iterator, it allows you to randomly jump to a position.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = array(&#13;
    'Head First Design Patterns',&#13;
    'Clean Code: A Handbook of Agile Software Craftsmanship',&#13;
    'Domain-Driven Design: Tackling Complexity in the Heart of Software',&#13;
    'Agile Software Development, Principles, Patterns, and Practices',&#13;
);&#13;
$booksAsArrayIterator = new ArrayIterator($books);&#13;
$booksAsArrayIterator-&gt;seek(3);&#13;
echo $booksAsArrayIterator-&gt;current();&#13;
// Output&#13;
Agile Software Development, Principles, Patterns, and Practices&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    At last, ArrayIterator is part of SPL whereas ArrayObject is not.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec5"&gt;5. Iterating the File System&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    It is a very common task to list outthe content of a given directory. PHP provides lots of&#13;
                    functions for handling a file system. One of them is scandir().&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Suppose we are given a task to list out all files in a given directory as below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;pre&gt;&#13;
---books&#13;
|   ---book_item_1.txt&#13;
|   ---book_item_2.txt&#13;
|   ---book_item_3.txt&#13;
|    ---book_item_4.txt&#13;
                &lt;/pre&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We can accomplish it through scandir() as shown below:&#13;
                &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = scandir("books");&#13;
foreach($books as $book) {&#13;
    echo $book . "\n";&#13;
}&#13;
// Output&#13;
.&#13;
..&#13;
book_item_1.txt&#13;
book_item_2.txt&#13;
book_item_3.txt&#13;
book_item_4.txt&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    These are two virtual directories("." and "..") you'll find in each directory of the file system.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As this chapter is about iterators, we are going to introduce some iterators for handling filesystem. Hopefully in your next project, you will be able to utilize some of them. Three iterators come in handy: DirectoryIterator, FilesystemIterator and RecursiveDirectoryIterator.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Before we look into each one of them, it is useful to take a look at their inherit relationship:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
DirectoryIterator extends SplFileInfo&#13;
FilesystemIterator extends DirectoryIterato&#13;
RecursiveDirectoryIterator extends FilesystemIterator&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;DirectoryIterator&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    To accomplish the same task, we can use DirectoryIterator:&#13;
                &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = new DirectoryIterator('books');&#13;
foreach($books as $book) {&#13;
    echo $book-&gt;getFilename() . "\n";&#13;
}&#13;
// Output&#13;
.&#13;
..&#13;
book_item_1.txt&#13;
book_item_2.txt&#13;
book_item_3.txt&#13;
book_item_4.txt&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The only parameter needed to create a DirectoryIterator object is a directory's path. Compared to scandir function, instead of the file name as a string, DirectoryIterator returns an object. The object holds various information relating to a file, which we can make use.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;strong&gt;FilesystemIterator&lt;/strong&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    To accomplish the same task by using FilesystemIterator, we can use:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = new FilesystemIterator('books');&#13;
foreach($books as $book) {&#13;
    echo $book-&gt;getFilename() . "\n";&#13;
}&#13;
// Output&#13;
book_item_1.txt&#13;
book_item_2.txt&#13;
book_item_3.txt&#13;
book_item_4.txt&#13;
&lt;/script&gt;&#13;
                &lt;p&gt;&#13;
                    This looks almost the same as DirectoryIterator, except that FilesystemIterator has automatically filtered out the two virtual directories.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Are they really the same? We can use a simple method to tell the differences:&#13;
                &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = new DirectoryIterator('books');&#13;
foreach($books as $key=&gt;$value) {&#13;
    echo $key . ' is a type of '. gettype($key) . "\n";&#13;
    echo $value . ' is a type of '. get_class($value) . "\n";&#13;
}&#13;
&#13;
echo '-------------------------'."\n";&#13;
&#13;
$books = new FilesystemIterator('books');&#13;
foreach($books as $key=&gt;$value) {&#13;
    echo $key . ' is a type of '. gettype($key) . "\n";&#13;
    echo $value . ' is a type of '. get_class($value) . "\n";&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The result of running above script from CLI is:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
0 is a type of integer&#13;
. is a type of DirectoryIterator&#13;
1 is a type of integer&#13;
.. is a type of DirectoryIterator&#13;
2 is a type of integer&#13;
book_item_1.txt is a type of DirectoryIterator&#13;
3 is a type of integer&#13;
book_item_2.txt is a type of DirectoryIterator&#13;
4 is a type of integer&#13;
book_item_3.txt is a type of DirectoryIterator&#13;
5 is a type of integer&#13;
book_item_4.txt is a type of DirectoryIterator&#13;
&#13;
--------------------------------&#13;
&#13;
books/book_item_1.txt is a type of string&#13;
books/book_item_1.txt is a type of SplFileInfo&#13;
books/book_item_2.txt is a type of string&#13;
books/book_item_2.txt is a type of SplFileInfo&#13;
books/book_item_3.txt is a type of string&#13;
books/book_item_3.txt is a type of SplFileInfo&#13;
books/book_item_4.txt is a type of string&#13;
books/book_item_4.txt is a type of SplFileInfo&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now we can see they are actually quite different internally:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;DirectoryIterator returns an integer as the key and a DirectoryIterator as the value in a loop.&lt;/li&gt;&#13;
                    &lt;li&gt;FilesystemIterator returns a string of full path as the key and a SplFileInfo object as the value in a loop.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In fact, FilesystemIterator comes with a bit more flexibility. When creating a FilesystemIterator object, it accepts a directory's path as the first parameter similar to DirectoryIterator. Moreover, you can optionally pass a second parameter as a flag. This flag is able to configure various aspects of this function.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;FilesystemIterator::CURRENT_AS_PATHNAME: This flag will make FilesystemIterator return file path instead of SplFileInfo object as the value.&lt;/li&gt;&#13;
                    &lt;li&gt;FilesystemIterator::CURRENT_AS_FILEINFO: This flag will make FilesystemIterator return SplFileInfo object as the value. This is the default behavior. You don't have to set it explicitly.&lt;/li&gt;&#13;
                    &lt;li&gt;FilesystemIterator::CURRENT_AS_SELF: This flag will make FilesystemIterator return FilesystemIterator itself as the value.&lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        FilesystemIterator::KEY_AS_PATHNAME: This flag will make FilesystemIterator return file path as the key. This is the default behavior. You don't have to set it explicitly.&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        FilesystemIterator::KEY_AS_FILENAME: This flag will make FilesystemIterator return file name and extension instead of file path as the key.&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        FilesystemIterator::FOLLOW_SYMLINKS: This flag will make RecursiveDirectoryIterator::hasChildren() follow symlinks.&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        FilesystemIterator::NEW_CURRENT_AND_KEY: This flag helps set two other flags(FilesystemIterator::KEY_AS_FILENAME and FilesystemIterator::CURRENT_AS_FILEINFO) at once.&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        FilesystemIterator::SKIP_DOTS: This flag will make FilesystemIterator ignore virtual directories ("." and "..").&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        FilesystemIterator::UNIX_PATHS: This flag will make FilesystemIterator use Unix style directory separator() despite what system the PHP script runs on.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec6"&gt;6. Peeking ahead with CachingIterator&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In this section, we will introduce an iterator with the ability of peeking into next element in an iteration. This feature enables us to do a lot useful things such as, executing something different when iterator reaches the end of the list.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The class with this great power is CachingIterator.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's first take a look at it class signature, then, we will go into details of its usage.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
CachingIterator extends IteratorIterator&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    CachingIterator inherits from IteratorIterator. What is IteratorIterator? It is simply a wrapper around another iterator, under the hood. It will forward the five Itertator methods( rewind() ,&#13;
                    current() , key() , valid() , next() ) calls to the iterator it wraps around. We can also retrieve the inner iterator by calling method getInnerIterator() .&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Due to the nature of this class, the inner iterator's pointer always moves one step ahead of CachingIterator, and CachingIterator provides a method hasNext() to tell us if it reaches the end of the list. That is how CachingIterator peeks ahead.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now, let's put it into action.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = array(&#13;
    'Head First Design Patterns',&#13;
    'Clean Code: A Handbook of Agile Software Craftsmanship',&#13;
    'Domain-Driven Design: Tackling Complexity in the Heart of Software',&#13;
    'Agile Software Development, Principles, Patterns, and Practices',&#13;
);&#13;
$booksAsCachingIterator = new CachingIterator(new ArrayIterator($books));&#13;
foreach ($booksAsCachingIterator as $book) {&#13;
    echo 'current book - ' . $book . PHP_EOL;&#13;
    if ($booksAsCachingIterator-&gt;hasNext()) {&#13;
        echo '----------------------------' . PHP_EOL;&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Result of running above script in a CLI:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
current book - Head First Design Patterns&#13;
next book - Clean Code: A Handbook of Agile Software Craftsmanship&#13;
&#13;
----------------------------&#13;
&#13;
current book - Clean Code: A Handbook of Agile Software Craftsmanship&#13;
next book - Domain-Driven Design: Tackling Complexity in the Heart of Software&#13;
&#13;
----------------------------&#13;
&#13;
current book - Domain-Driven Design: Tackling Complexity in the Heart of Software&#13;
next book - Agile Software Development, Principles, Patterns, and Practices&#13;
&#13;
----------------------------&#13;
&#13;
current book - Agile Software Development, Principles, Patterns, and Practices&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Similar to other iterators, to create an CachingIterator instance, we pass in an iterator as the first parameter to the class contractor. As we can see, the real magic behind peeking ahead is provided by method hasNext() . This method is able to tell us if there is an immediate next element.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Beside the first parameter, CachingIterator also optionally accepts a second parameter as a flag.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;CachingIterator::CALL_TOSTRING: It will return __toString of the current element as value. This is the default behavior.&lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        CachingIterator::CATCH_GET_CHILD: It will capture all exceptions thrown when accessing children.&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        CachingIterator::TOSTRING_USE_KEY: It will return the key value when casting the iterator to a string in a loop.&#13;
                    &lt;/li&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = array(&#13;
    'Head First Design Patterns',&#13;
    'Clean Code: A Handbook of Agile Software Craftsmanship',&#13;
    'Domain-Driven Design: Tackling Complexity in the Heart of Software',&#13;
    'Agile Software Development, Principles, Patterns, and Practices',&#13;
);&#13;
&#13;
$booksAsCachingIterator = new CachingIterator(new ArrayIterator($books), CachingIterator::TOSTRING_USE_KEY;&#13;
&#13;
foreach ($booksAsCachingIterator as $key=&gt;$book) {&#13;
    echo $booksAsCachingIterator . PHP_EOL;&#13;
}&#13;
// Output 0&#13;
1&#13;
2&#13;
3&#13;
                &lt;/script&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        CachingIterator::TOSTRING_USE_CURRENT: It will return the current value when casting the iterator to a string in a loop.&#13;
                    &lt;/li&gt;&#13;
&#13;
&#13;
                    &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$books = array(&#13;
    'Head First Design Patterns',&#13;
    'Clean Code: A Handbook of Agile Software Craftsmanship',&#13;
    'Domain-Driven Design: Tackling Complexity in the Heart of Software',&#13;
    'Agile Software Development, Principles, Patterns, and Practices',&#13;
);&#13;
&#13;
$booksAsCachingIterator = new CachingIterator(new ArrayIterator($books), CachingIterator::TOSTRING_USE_CURRENT);&#13;
&#13;
foreach ($booksAsCachingIterator as $key=&gt;$book) {&#13;
    echo $booksAsCachingIterator . PHP_EOL;&#13;
}&#13;
// Output&#13;
Head First Design Patterns&#13;
Clean Code: A Handbook of Agile Software Craftsmanship&#13;
Domain-Driven Design: Tackling Complexity in the Heart of Software&#13;
Agile Software Development, Principles, Patterns, and Practices&#13;
                    &lt;/script&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        CachingIterator::TOSTRING_USE_INNER: It will return the inner iterator casted to a string when casting the iterator to a string in a loop. If we set this flag in the same code as previous example, it will throw an exception. This is because ArrayIterator does not implement the __toString() method.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        CachingIterator::FULL_CACHE: A CachingIterator won't have a key word "caching" in its name if it is not able to do some sort of cache. When this flag is set, it will cache the results, should they ever be iterated for future use.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec7"&gt;7. Generator&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    You are now convinced by the benefits of iterators. They encapsulate the details of traversing and they are much more efficient than creating in-memory arrays. However, everything has its price. To create an iterator, we still have to implement the SPL Iterator interface. You might be terrified of iterators and not want to implement those five methods contracted by Iterator interface. It is time consuming and sometimes even complex to implement them.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Starting from PHP 5.5, you won't be intimidated any more. PHP introduces something, Generators, which provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
&#13;
                    What is exactly a generator? A generator is like a normal PHP function, except that it has a special keyword , "yield", in it.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Below is a simple example of a generator function. We won't have such a generator in the real world application - it is here for demonstration only:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
function booksGenerator()&#13;
{&#13;
    $books = array(&#13;
        'Head First Design Patterns',&#13;
        'Clean Code: A Handbook of Agile Software Craftsmanship',&#13;
        'Domain-Driven Design: Tackling Complexity in the Heart of Software',&#13;
        'Agile Software Development, Principles, Patterns, and Practices',&#13;
    );&#13;
&#13;
    foreach ($books as $book) {&#13;
        yield $book;&#13;
    }&#13;
}&#13;
&#13;
foreach (booksGenerator() as $book) {&#13;
    echo $book . PHP_EOL;&#13;
}&#13;
&#13;
// Output&#13;
Head First Design Patterns&#13;
Clean Code: A Handbook of Agile Software Craftsmanship&#13;
Domain-Driven Design: Tackling Complexity in the Heart of Software&#13;
Agile Software Development, Principles, Patterns, and Practices&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Internally PHP realizes a generator function when it spots the yield keyword. When a generator function is called for the first time, PHP creates a Generator object. This Generator object is an instance of an internal class Generator and Generator class implements the Iterator interface. This way, users are able to create iterators without writing the contracted code, all thanks to PHP generator.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The yield is called when we need to provide the step values. Think of it as return in a function or current method in a regular iterator.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's turn one of our first iterator class TrendingRepositoriesIterator to a generator function:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
function trendingRepositoriesGenerator()&#13;
{&#13;
    $client = new GuzzleHttp\Client();&#13;
    $res = $client-&gt;request('GET', 'https://api.github.com/search/repositories', [ 'query' =&gt; ['q' =&gt; 'language:php', 'sort' =&gt; 'stars', 'order' =&gt; 'desc'] ]);&#13;
    $resInArray = json_decode($res-&gt;getBody(), true);&#13;
    $trendingRepos = array_slice($resInArray['items'], 0, 10);&#13;
    foreach ($trendingRepos as $rep) {&#13;
        yield $rep['name'];&#13;
    };&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    It turns out to be much less code with a generator. We can also use it in a foreach loop, in the same way as we did with TrendingRepositoriesIterator:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
foreach (trendingRepositoriesGenerator() as $repo) {&#13;
    echo $repo . PHP_EOL;&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Note that generators themselves do not provide anything special - they just make creating iterators simpler. In other words, they are definitely not replacements for iterators.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec8"&gt;8. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt; and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    Did we miss out anything? Do leave a comment below to let us know.&#13;
                &lt;/p&gt;&#13;
</description><pubDate>Mon, 05 Feb 2018 13:41:43 +0000</pubDate></item><item><title>Modern PHP Developer - PDO</title><link>https://www.startutorial.com/articles/view/modern-php-developer-pdo</link><guid>https://www.startutorial.com/articles/view/modern-php-developer-pdo<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    PHP Data Objects, most commonly known as PDO, is a PHP extension built to solve database access&#13;
                    problems. It provides a unified interface to access databases.&#13;
                    &lt;br&gt;&lt;br&gt;&#13;
                    PDO creates an abstraction layer for data-access, so developers can write portable code without&#13;
                    worrying about the underlying database engines. In layman's terms, you use PDO to develop an&#13;
                    application using MySQL as the database storage. If you want to switch to PostgreSQL at any point in&#13;
                    time, all you need to do is to change the PDO driver. No other code change is required.&#13;
                    &lt;br&gt;&lt;br&gt;&#13;
                    PDO consists of three main types of objects: They are PDO object, PDOStatement object and&#13;
                    PDOException object. We should not necessarily neglect the PDO Drivers, but these three types of&#13;
                    objects together form the main interface of the PDO extension.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Why use PDO?&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Running PDO Queries&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Data manipulation&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;PDO API&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec5"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Why use PDO?&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you have developed any MySQL database driven application before, but have never tried PDO, you must be wondering what the benefits are to use PDO, especially when comparing it to its two alternatives.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;MySQL&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The oldest way to interact with MySQL is to use mysql extension. It was introduced in PHP 2.0.0, however it was deprecated as of PHP 5.5.0, and has already been removed in PHP 7.0.0. It is not recommended to use this extension at all given the factor that it is not supported in newer PHP versions.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;MySQLi&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Since PHP 5.0.0, an improved version of &lt;code&gt;mysql&lt;/code&gt; extension, known as &lt;code&gt;mysqli&lt;/code&gt; was introduced. It brought a lot of benefits over the &lt;code&gt;mysql&lt;/code&gt; extension, such as object-oriented interface, prepare statements, multiple statements, transaction support, enhanced debugging capabilities and embedded server support.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The main differences between MySQLi and PDO are:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;PDO supports client-side prepared statements, whereas MySQLi does not. We will discuss client-side prepare statements in details in later sections. It basically means it will emulate prepared statement if the chosen database server does not support it.&lt;/li&gt;&#13;
                    &lt;li&gt;MySQLi supports both object-oriented API and procedural API, whereas PDO religiously uses objected-oriented API.&lt;/li&gt;&#13;
                    &lt;li&gt;The biggest advantage of using PDO is to write portable code. It enables developers to switch databases easily, whereas MySQLi only supports the MySQL database.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Ultimately, we recommend using PDO to build your applications.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&#13;
                        It enables developers to write portable code.&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        It encourages object-oriented programming.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&#13;
                    Lastly, we want to emphasize that, by no means are you forbidden to use MySQLi.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In the following sections, we will start with some common ways of running queries using PDO. Then we will demonstrate how to perform various MySQL data manipulation statements using PDO. Finally, we will focus on a few PDO APIs, which serve the same purpose but in different ways.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Running PDO Queries &lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We summarize the different ways of running PDO queries into four categories, classified by number of steps involved from carrying out the query to getting its result. These categories were created to ease the efforts of remembering PDO APIs and include:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;exec&lt;/li&gt;&#13;
                    &lt;li&gt;query fetch&lt;/li&gt;&#13;
                    &lt;li&gt;prepare execute fetch&lt;/li&gt;&#13;
                    &lt;li&gt;prepare bind execute fetch&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Establish database connection&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Before we get into each category, you will first need to be familiar yourself with establishing a database connection using PDO. This is the absolute the fundamental of PDO, as it is used in every piece of code below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
try {&#13;
    $dbh = new PDO('mysql:host=localhost;dbname=customers', $user, $pass);&#13;
} catch (PDOException $e) {&#13;
    die($e-&gt;getMessage());&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    To establish a database connection, we instantiate a PDO object with three parameters. The first parameter specifies a database source (known as the DSN), which consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. The second and third parameters are database username and password.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    An exception will be thrown if the connection fails. You can catch the exception and handle it gracefully. Kudos to exception in this case, we no longer need to put the connection in a if statement due to a clean and easy to read code base.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In the following code samples, we will neglect this piece of code, to avoid clutter. Keep in mind, you will always need to make the connection first before proceeding with any PDO operations.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;exec&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This is the simplest form of running a query. We can use it to run a quick query and normally we do not expect it to return any results.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$dbh-&gt;exec('INSERT INTO customers VALUES (1, "Andy")');&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Though PDO::exec does not return the result corresponding to your query, it does return something. Regardless of what query you run with PDO::exec, it returns the number of affected rows on success. It also returns Boolean FALSE on failure.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A caveat when checking the return type: since it PDO::exec returns 0 when there is no row affected, we should always use === comparison operator to verify success of running the method.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
if (FALSE === $dbh-&gt;exec('INSERT INTO customers VALUES (1, "Andy")')) {&#13;
    throw new MyException('Invalid sql query');&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you are building the query string with user input and manually handling security issues as such escaping characters, you should use other alternatives, which we will discuss later.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;query fetch&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    When running query such as SELECT statement, we do expect a return of corresponding results. The easiest way of accomplishing this is use:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$statement = $dbh-&gt;query('SELECT * FROM customers');&#13;
while ($row = $statement-&gt;fetch(PDO::FETCH_ASSOC)) {&#13;
    echo $row['id'] . ' ' . $row['name'] . PHP_EOL;&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Note that methods &lt;code&gt;$dbh-&gt;query()&lt;/code&gt; and &lt;code&gt;$statement-&gt;fetch()&lt;/code&gt; , are how we name our categories, by the sequences of calling PDO APIs.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Because PDO::query returns a result set as a PDOStatement object on success (It will return Boolean FALSE on failure, do similar check as PDO::exec if you want to verify). PDOStatement class implements the Traversable interface, which is the base interface for Iterator, meaning it can be used in an iteration statement as such as a &lt;code&gt;loop&lt;/code&gt; . Naturally, there is a short version of previous code:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
foreach ($dbh-&gt;query('SELECT * FROM customers', PDO::FETCH_ASSOC) as $row) {&#13;
    echo $row['id'] . ' ' . $row['name'] . PHP_EOL;&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    You might have noticed, when calling either PDO::query or PDOStatement::fetch, we have supplied a flag parameter. This parameter specifies what type of data structure we want from the callee.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A few of the options include:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;PDO::FETCH_ASSOC: returns an associative array indexed by column name.&lt;/li&gt;&#13;
                    &lt;li&gt;PDO::FETCH_NUM: returns an numerically indexed array.&lt;/li&gt;&#13;
                    &lt;li&gt;PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0- indexed column number as returned in your result set. (Combination of PDO::FETCH_ASSOC and PDO::FETCH_NUM).&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    There are a lot more options. We recommended that you take a quick look at them at PHP Manual. Though this parameter is optional, we should always specify it unless we really want an array indexed by both column name and number. PDO::FETCH_BOTH takes twice as much memory.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;prepare execute fetch&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We frequently need to accept user's input in order to run a database query. There are two&#13;
                    major concerns if we were to use A &lt;code&gt;query fetch&lt;/code&gt; approach.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    First, we will have to make sure the sql query passed to PDO::query is safe. Escaping and quoting the input values must be well taken care of. Second, PDO::query executes an SQL statement in a single function call, which means if we need to run the same query multiple times, it will use multiple times of resources. There is a better way of doing this.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    PDO introduces prepare statement for the first time. So what is prepare statement? According to Wikipedia.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;blockquote&gt;&#13;
                    In database management systems, a prepared statement or parameterized statement is a feature used to execute the same or similar database statements repeatedly with high efficiency. Typically used with SQL statements such as queries or updates, the prepared statement takes the form of a template into which certain constant values are substituted during each execution.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Prepare statement solves two concerns raised above. It not only improves the efficiency of running multiple similar queries, but also takes care of escaping and quoting user input values.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Below is how we implement prepare statement using PDO:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$users = ['Andy', 'Tom'];&#13;
$statement = $dbh-&gt;prepare('SELECT * FROM customers where name = :name');&#13;
foreach ($users as $user) {&#13;
    $statement-&gt;execute([':name' =&gt; $user]);&#13;
    while ($row = $statement-&gt;fetch(PDO::FETCH_ASSOC)) {&#13;
        echo $row['id'];&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Note the steps we have taken here:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;PDO::prepare is used to create a sql query containing a variable parameter. Naming convention for parameters are either named variables prefixed by a colon(:) or a question mark (?).&lt;/li&gt;&#13;
                    &lt;li&gt;PDOStatement::execute is called to execute a query with parameters' value. When ? is used in the prepare statement, they are numbered parameters. We can bind the values using a numeric indexed array. Note in the foreach , it uses the same statement to carry out the query after binding the value. It returns Boolean FALSE upon failure. We can use PDOStatement::errorInfo() to get the error information associated with the operation.&lt;/li&gt;&#13;
                    &lt;li&gt;PDOStatement::fetch is used to fetch result with desired data structure.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;prepare bind execute fetch&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A minor issue you might have OBSERVED in previous code is what happens when there are a lot of parameters in the prepare statement. We can easy create code piece like this:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$statement-&gt;execute([':name' =&gt; $user, ':mobile' =&gt; $mobile, ':address' =&gt; $address ]);&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The list can go on and on. This makes code very difficult to read. However, a more important thing to notice here is that, PHP will cast user input value to match its database field type if they do not match exactly, which is prone to bugs.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Here is where PDOStatement::bindValue comes in to save. The recommended way of running previous is:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$users = ['Andy', 'Tom'];&#13;
$statement = $dbh-&gt;prepare('SELECT * FROM customers where name = :name');&#13;
foreach ($users as $user) {&#13;
    $statement-&gt;bindValue(':name', $user, PDO::PARAM_STR);&#13;
    $statement-&gt;execute();&#13;
    while ($row = $statement-&gt;fetch(PDO::FETCH_ASSOC)) {&#13;
        echo $row['id'];&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Instead of using PDOStatement::execute to bind value to parameter, we used PDOStatement::binValue. It adds a few significant improvements to our code:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                   &lt;li&gt;Readability: it makes the code easy to read for other developers, as it indicates the exact data type a parameter should accept.&lt;/li&gt;&#13;
                   &lt;li&gt;Maintainability: The third parameter, which specifies datatype of passing variable, prevents PHP from casting incompatible datatype, which is prone to bug. In the long run, it also makes the code easier to maintain, as future developer will be able to spot the datatype at a glance.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    These four techniques are definitely not official: they are just naming conventions made to memorize PDO APIs. There is no need to follow them strictly. In fact, most of time we combine these techniques together.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
&#13;
&#13;
&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. Data manipulation&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's put what we have learned into action. In this section, we will use PDO to accomplish some of the most common MySQL tasks.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Sample database table&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We will need a database table to play around with.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    For demonstration purpose, we will create a very simple database table:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
CREATE TABLE IF NOT EXISTS `customers` (&#13;
`id` int(11) NOT NULL AUTO_INCREMENT,&#13;
`name` varchar(100) NOT NULL,&#13;
PRIMARY KEY (`id`)&#13;
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Insert data&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Our first task is to insert some data into the table. For this use case, let's suppose we accept data from a user input form via a POST request, and then we insert whatever data is from the form into the customers table.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
try {&#13;
    $dbh = new PDO('mysql:host=localhost;dbname=inventory', 'root', 'root');&#13;
} catch (PDOException $e) {&#13;
    die($e-&gt;getMessage());&#13;
}&#13;
&#13;
$name = $_POST['name'];&#13;
&#13;
$statement = $dbh-&gt;prepare('INSERT INTO customers (name) VALUES (:name)');&#13;
&#13;
if (false === $statement) {&#13;
    throw new Exception('Invalid prepare statement');&#13;
}&#13;
&#13;
if (false === $statement-&gt;execute([':name' =&gt; $name])) {&#13;
    throw new Exception(implode(' ', $statement-&gt;errorInfo()));&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We are using the prepare-&gt;execute-&gt;fetch techinique in this code sample, except we removed the fetch part since we do not expect it to return any result set.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;The first step is to connect to the database as usual.&lt;/li&gt;&#13;
                    &lt;li&gt;Then, we create a prepare statement. Note that we also handle failure case by throwing an exception.&lt;/li&gt;&#13;
                    &lt;li&gt;And lastly, we execute the prepare statement. Failure case is also handled. We are able to output useful information by calling PDOStatement::errorInfo method.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Update data&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;The second common task is to update existing data. Assume the use case is the same as the previous case, except the user is able to pass in an additional parameter ($id).&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
try {&#13;
    $dbh = new PDO('mysql:host=localhost;dbname=inventory', 'root', 'root');&#13;
} catch (PDOException $e) {&#13;
    die($e-&gt;getMessage());&#13;
}&#13;
$id = $_POST['id'];&#13;
$name = $_POST['name'];&#13;
$statement = $dbh-&gt;prepare('UPDATE customers SET name = :name WHERE id = :id');&#13;
if (false === $statement) {&#13;
    throw new Exception('Invalid prepare statement');&#13;
}&#13;
if (false === $statement-&gt;execute([':name' =&gt; $name, ':id' =&gt; $id])) {&#13;
    throw new Exception(implode(' ', $statement-&gt;errorInfo()));&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As you have probably guessed, beside the additional parameter $id ,the code is identical to previous code sample.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Delete&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The third common task is to delete an existing data record (similar use case here). User is able to pass in a single parameter ($id), and the corresponding record should be deleted.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
try {&#13;
    $dbh = new PDO('mysql:host=localhost;dbname=inventory', 'root', 'root');&#13;
} catch (PDOException $e) {&#13;
    die($e-&gt;getMessage());&#13;
}&#13;
$id = $_POST['id'];&#13;
$statement = $dbh-&gt;prepare('DELETE from customers WHERE id = :id');&#13;
if (false === $statement) {&#13;
    throw new Exception('Invalid prepare statement');&#13;
}&#13;
if (false === $statement-&gt;execute([':id' =&gt; $id])) {&#13;
    throw new Exception(implode(' ', $statement-&gt;errorInfo()));&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Again, this is a very similar code sample as the previous one (prepare-&gt;execute-&gt;fetch techinique with fetch part). That is the "beautify" of PDO - its object-oriented design makes code easy to write.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Select&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Our final task is to select all data records from customers, but this time, we won't ask for user's input.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
try {&#13;
    $dbh = new PDO('mysql:host=localhost;dbname=inventory', 'root', 'root');&#13;
} catch (PDOException $e) {&#13;
    die($e-&gt;getMessage());&#13;
}&#13;
$results = array();&#13;
$statement = $dbh-&gt;query('SELECT * FROM customers');&#13;
if (false === $statement) {&#13;
    throw new Exception('Invalid query');&#13;
}&#13;
while ($row = $statement-&gt;fetch(PDO::FETCH_ASSOC)) {&#13;
    $results[] = $row['name'];&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In this example, we have used the query-&gt;fetch technique. As we mentioned earlier and it is worth mentioning again, when calling PDOStatement::fetch, it is a good habit to always specify the fetch mode.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now we have run through some quick samples of using PDO for various tasks. These samples are very simple, yet they have showed us a very easy to use and consistent API provided by PDO.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. PDO API&lt;/h6&gt;&#13;
                &lt;p&gt;&#13;
                    So far, we have demonstrated some common PDO APIs. PDO still provides a lot more than we have shown above. In this section, we will explore PDO APIs for the last time and try to cover as many useful APIs as we can. It is nearly impossible to cover every aspect of this topic but always keep in mind that there is a manual page that can be referenced when you are in doubt.&#13;
                    (&lt;a href="http://php.net/manual/en/class.pdo.php"&gt;PDO Manual page&lt;/a&gt;)&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Fetch methods&lt;/strong&gt;&lt;/p&gt;&#13;
                &lt;p&gt;&#13;
                    We have covered one(PDOStatement::fetch) of the fetching methods used to retrieve result sets. In fact, PDOStatement provides three additional fetching methods.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;PDOStatement::fetchAll&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Working similarly to PDOStatement::fetch, PDOStatement::fetchAll also accepts a flag as first parameter, which is to specify fetch mode. We should always specify the fetch mode the same way we do for PDOStatement::fetch method. It differs from PDOStatement::fetch in that it returns all result at once.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$statement = $dbh-&gt;query('SELECT * FROM customers');&#13;
$result = $statement-&gt;fetchAll(PDO::FETCH_ASSOC);&#13;
print_r($result);&#13;
// Output&#13;
Array&#13;
(&#13;
    [0] =&gt; Array (&#13;
            [id] =&gt; 2&#13;
            [name] =&gt; TEST2&#13;
        )&#13;
    [1] =&gt; Array (&#13;
            [id] =&gt; 3&#13;
            [name] =&gt; TEST2&#13;
        )&#13;
    [2] =&gt; Array (&#13;
        [id] =&gt; 4&#13;
        [name] =&gt; TEST2&#13;
    )&#13;
)&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;A caveat of this method is that, since it loads all result sets at once, it might result in heavy memory usage depending on how much data is available. You should use this method with attention.&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;PDOStatement::fetchColumn&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A handy method for retrieving data from the desired column is PDOStatement::fetchColumn. It returns a single column from the next row of a result set. It is similar to PDOStatement::fetch, however it returns the next single column only instead of a next array of result reset.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$statement = $dbh-&gt;query('SELECT id, name FROM customers');&#13;
while($result = $statement-&gt;fetchColumn(1)) {&#13;
    echo $result . PHP_EOL;&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    PDOStatement::fetchColumn accepts a single parameter(column name) optionally. The parameter is a 0-indexed number specifying the column to retrieve data from. When this parameter is omitted, it defaults to column number 0.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Two points to not when using this method:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;PDOStatement::fetchColumn will return Boolean FALSE when it reaches the end of the result set, so it should not be used to retrieve Boolean type from the database.&lt;/li&gt;&#13;
                    &lt;li&gt;PDOStatement::fetchColumn moves its pointer one step forward when it is called, so there is no way to retrieve another column from the same row. (Obviously the pointer has already moved to the next row when we call it using different column number).&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;PDOStatement::fetchObject&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This method is an alternative to PDOStatement::fetch() with PDO::FETCH_CLASS or PDO::FETCH_OBJ style. Its purpose is to make our code easier to read when called separately, when this method is called, it will return next result set as a PHP object:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$statement = $dbh-&gt;query('SELECT id, name FROM customers');&#13;
while($object = $statement-&gt;fetchObject()) {&#13;
    print_r($object);&#13;
}&#13;
// Output&#13;
stdClass Object&#13;
(&#13;
    [id] =&gt; 2&#13;
    [name] =&gt; TEST2&#13;
)&#13;
stdClass Object&#13;
(&#13;
    [id] =&gt; 3&#13;
    [name] =&gt; TEST2&#13;
)&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We can also pass in our custom PHP class as first parameter, PHP will instantiate one instance of our custom PHP object with data retrieved and return it:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class MyClass&#13;
{&#13;
}&#13;
$statement = $dbh-&gt;query('SELECT id, name FROM customers');&#13;
while($object = $statement-&gt;fetchObject('MyClass')) {&#13;
    print_r($object);&#13;
}&#13;
// Output&#13;
MyClass Object&#13;
(&#13;
    [id] =&gt; 2&#13;
    [name] =&gt; TEST2&#13;
)&#13;
MyClass Object&#13;
(&#13;
    [id] =&gt; 3&#13;
    [name] =&gt; TEST2&#13;
)&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Bind methods:&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Previously, we have used PDOStatement::bindValue. This method binds desired value to the placeholder of the query. This method is not the only method for that task though.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;bindParam&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This method is almost identical to PDOStatement::bindValue and it's no surprise that some people use these two methods interchangeably, however there is a very significant different between these two methods, and it might cost you a fortune if you are not aware of it.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's see what it means by example.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$user = 'Andy';&#13;
$statement = $dbh-&gt;prepare('SELECT * FROM customers where name = :name');&#13;
$statement-&gt;bindValue(':name', $user, PDO::PARAM_STR);&#13;
$user = 'Tom';&#13;
$statement-&gt;execute();&#13;
echo $statement-&gt;fetchColumn(1);&#13;
// Output&#13;
Andy&#13;
&#13;
$user = 'Andy';&#13;
$statement = $dbh-&gt;prepare('SELECT * FROM customers where name = :name');&#13;
$statement-&gt;bindParam(':name', $user, PDO::PARAM_STR);&#13;
$user = 'Tom';&#13;
$statement-&gt;execute();&#13;
echo $statement-&gt;fetchColumn(1);&#13;
// Output Tom&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Do you spot the difference? These two pieces of code are identical except one is using $statement-&gt;bindParam and the other is using $statement-&gt;bindValue. The result produced is entirely different.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    PDOStatement::bindParam binds variable $user as a reference. At the time of PDOStatement::execute is called, $user variable is changed to 'Tom' whereas PDOStatement::bindParam variable as a value, it remains as 'Andy' from the time PDOStatement::bindValue is called.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Make sure you understand the difference between these two and choose them according to your needs. Switching these two methods without a fair amount of consideration is discouraged.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;bindColumn&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Different from PDOStatement::bindValue and PDOStatement::bindParam, this method is not a method for binding variable to prepare statement. In fact, it is quite the opposite: it binds columns from resulting set to PHP local variables.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This is an interesting method to observe. Previously, we discussed that a method PDOStatement::fetchObject, can return result set as a defined object. Here, with PDOStatement::bindColumn, we can bind columns from result set to variables.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$statement = $dbh-&gt;prepare('SELECT id, name FROM customers');&#13;
$statement-&gt;bindColumn('name', $name);&#13;
$statement-&gt;execute();&#13;
while ($statement-&gt;fetch(PDO::FETCH_ASSOC)) {&#13;
    echo $name . PHP_EOL;&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The first parameter which specifies the table column, accepts both string column name and 0-indexed number as a value. So the following is valid too.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$statement-&gt;bindColumn(1, $name);&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Conditions:&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In the last section, we will discuss some tips when working with PDO.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;IN clause&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Building IN clause in a prepare statement is an interesting task. Take a look at following code and imagine this is what we need to build:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$users = ['Andy', 'Tom'];&#13;
$statement = $dbh-&gt;prepare('SELECT * FROM customers where name IN :name');&#13;
$statement-&gt;execute($user);&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&#13;
&#13;
                    At first glance, it seems legitimate. Take a closer look. It won't work because prepare statement only accepts scalar types (e.g. string, int and so on).&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The ultimate task becomes building a comma separated string containing equal question marks(?) to the binding array variable. This is how we can build a legit IN clause string.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$users = ['Andy', 'Tom'];&#13;
$placeholder = implode(',', array_fill(0, count($users), '?'));&#13;
$statement = $dbh-&gt;prepare('SELECT * FROM customers where name IN '. $placeholder); $statement-&gt;execute($users);&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Wildcard characters&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    When building a LIKE clause, we might be tempted to do this:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$name = 'Andy';&#13;
$statement = $dbh-&gt;prepare('SELECT count(*) FROM customers where name LIKE %:name%');&#13;
$statement-&gt;bindValue(':name', $name);&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    However, that won't work in PDO. We need to shift the wildcard characters to the variable itself:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$name = '%Andy%';&#13;
$statement = $dbh-&gt;prepare('SELECT count(*) FROM customers where name LIKE :name');&#13;
$statement-&gt;bindValue(':name', $name);&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec5"&gt;5. The end&lt;/h6&gt;&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    Did we miss out anything? Do leave a comment below to let us know.&#13;
                &lt;/p&gt;</description><pubDate>Mon, 05 Feb 2018 13:40:17 +0000</pubDate></item><item><title>Modern PHP Developer - PSR</title><link>https://www.startutorial.com/articles/view/modern-php-developer-psr</link><guid>https://www.startutorial.com/articles/view/modern-php-developer-psr<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Prior to PHP Standards Recommendation (PSR), there were no truly uniformed standards for writing PHP code. For instance, for coding style, some people preferred Zend Framework Coding Standard, and some liked PEAR Coding Standards, and still others chose to create their own naming conventions and coding style.&#13;
                    &lt;br&gt;&lt;br&gt;&#13;
                    A group of people, representing various popular PHP projects came together in 2009 and formed something called Framework Interoperability Group(FIG). The purpose of FIG is for project representatives to talk about the commonalities between their projects and find ways to work together.&#13;
                    &lt;br&gt;&lt;br&gt;&#13;
                    At the time of this writing, there are six accepted PSRs: two of them are about autoloading, two of them are related to PHP coding style and the remaining are about interfaces.&#13;
                    &lt;br&gt;&lt;br&gt;&#13;
                    In this chapter, we will discuss each PSR briefly. The purpose of this chapter is to introduce you to the ideas of PSRs. For further details on each one, the respective link are provided.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;PSR-0 &amp; PSR-4&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;PSR-1 &amp; PSR-2&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;PSR-3 &amp; PSR-7&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;PSR Specifications&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec5"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. PSR-0, PSR-4&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Both PSR-0 and PSR-4 are standards for autoloading. If you aren't familiar with autoloading, it is basically a way for PHP to include classes without writing cluttered &lt;code&gt;include/require&lt;/code&gt; statements everywhere.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's take a look at the history of autoloading. This will give you a clear picture how autoloading in PHP has involved during the years.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In PHP language, we have to make sure a class's definition is loaded prior to using it. Normally, we will create our PHP classes in their own class files for better organization. Then we will load them with &lt;code&gt;require&lt;/code&gt; or &lt;code&gt;include&lt;/code&gt; statements in the files they are being called.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
include 'manager.php';&#13;
$manager = new Manager();&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This approach quickly raises some issues. Imagine you have tens of external classes to be used in a file and you start writing lines of &lt;code&gt;require/include&lt;/code&gt; statements right at the beginning of a source file. They are ugly and clutter our codebase with repetitive lines of include statements.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Starting in PHP 5, a new magic function was introduced to solve this issue:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
void __autoload ( string $class);&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;code&gt;__autoload&lt;/code&gt; is essentially a helper function, doing what we were doing with include statements. We can define this function anywhere in our codebase, and PHP will automatically use this function to load a class's file when an undefined class is called. This is the last chance to load a class definition before PHP fails with an error.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
function __autoload($class)&#13;
{&#13;
    $filename = 'classes/' . $class . '.php';&#13;
    if (file_exists($filename)) {&#13;
     include_once($filename);&#13;
    }&#13;
}&#13;
$manager = new Manager();&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;code&gt;__autoload&lt;/code&gt; quickly became obsolete due to the fact that it can only allows one autoloader function. What this means is that since &lt;code&gt;autoload&lt;/code&gt; is the one and the only one magic that PHP engine will call, we need to define this particular magic function wherever we want an autoloading feature. Theoretically, this includes every file in a solid object-oriented codebase.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    PHP 5.1.2 was shipped with another autoloading function( &lt;code&gt;spl_autoload_register&lt;/code&gt; ) for coping with &lt;code&gt;__autoload&lt;/code&gt; 's limitation. &lt;code&gt;spl_autoload_register&lt;/code&gt; is a replacement for&#13;
                    &lt;code&gt;__autoload&lt;/code&gt; , and it provides more flexibility. It works by registering PHP user land functions with the autoload queue. It effectively creates a queue of autoload functions, and runs through each of them in the order in which they are defined. This means we can have multiple autoloader functions and there is no need for creating &lt;code&gt;autoload&lt;/code&gt; function in each one of our source files anymore.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Autoloading was such a great idea that every project started to use it. Inevitably everyone created their own version of autoloader as uniform standards were lacking. Clearly, PHP desperately needed a standard for autoloader, which is how PSR-0 was born.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Today, Autoloader standard has evolved significantly. Even PSR-0 is officially depreciated due to some constraints, such as its unfriendiness to Composer.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The latest accepted autoloader standard is PSR-4. You should follow PSR-4 to create your desired autoloader. For specification of PSR-4, please read more from its &lt;a href="http://www.php-fig.org/psr/psr-4/"&gt;official page&lt;/a&gt;.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. PSR-1, PSR-2&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    PSR-1 and PSR-2 are for PHP coding standards. PSR-1 focuses on the basics, whereas PSR-2 expands upon PSR-1 and provides a more comprehensive coding style guide.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    PSR-1 lists a set of simple rules for naming conventions and file structures. Its main purpose is to ensure a high level of technical interoperability between shared PHP codes. In a project that is incorporated with various packages, it can be a mess if each uses different coding standard, which is what PRS-1 was designed to solve.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A quick overview of PSR-1:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&#13;
                        Files MUST use only &amp;lt;?php and &amp;lt;?= tags.&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        Files MUST use only UTF-8 without BOM for PHP code.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Files SHOULD either declare symbols (classes, functions, constants, etc.)&#13;
                        or cause sid effects(e.g. generate output, change .ini settings, etc.)&#13;
                        but SHOULD NOT do both.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Namespaces ad classes MUST follow PSR-0.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Class names MUST be declared in StydlyCaps.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Class constants MUST be declared in all upper case with underscore separators.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Method names MUST be declared in camelCase.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Building on top of PSR-1, PSR-2 provides more comprehensive guidelines with more detailed rules as basic as code indention. It also covers varicose aspects of coding style, from naming conventions to namespace, classes, properties, methods, control structures and closures. It is possible to find any specification you need from PSR-2. Adapting your codebase to this standard for interoperability is highly encouraged.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. PSR-3, PSR-7&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    After autoloading and coding standards, we can finally associate PSR with PHP code. These are PSR-3 and PSR-7. PSR-3 contains a logger interface and PSR-7 contains interfaces for HTTP message interfaces.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;PSR-3&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    PHP desperately needed a standard for Logger interface before PSR-3. Logging is such a common task that every project built its own version of logger. Without a standard, the only way to use a third-party logger was to write a wrapper around it, so it could work with our existing codebases. It was not only a painful process, but also felt wrong, because after all, they were all doing the same type of work: logging. We should be able to switch them around.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    PSR-3 provides common interface for logging libraries. As long as they implement the PSR-3 logger interface, they should be theoretically interchangeable with any other PSR-3 logger libraries.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's take a look how PSR-3 Logger interface improves our code reusability in a concrete example.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Suppose we have written a simple authentication class User below. It appends an audit message to a log file once an user logins in successfully. It is using our custom logger class, which exposes a single method &lt;code&gt;addMessage&lt;/code&gt; .&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class User&#13;
{&#13;
    private $logger;&#13;
&#13;
    public function __construct($logger)&#13;
    {&#13;
        $this-&gt;logger = $logger;&#13;
    }&#13;
&#13;
    public function login($username, $password)&#13;
    {&#13;
        if ($this-&gt;validUsernameAndPassword($username, $password)) {&#13;
            $this-&gt;logger-&gt;addMessage('login');&#13;
        }&#13;
    }&#13;
&#13;
    private function validUsernameAndPassword($username, $password)&#13;
    {&#13;
        // ... ...&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Our custom Logger class is injected to User class following dependency injection principle, this seems to make our User reusable. We can switch to other logger class simply via the constructor. But if we take a look closely, we can't do that, User class is still highly coupled to our custom Logger class, it is aware of custom method &lt;code&gt;addMessage&lt;/code&gt; . If we use another third-party logger library in our code, it won't work, because they do not have a method called &lt;code&gt;addMessage&lt;/code&gt;.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;We can modify our code to use PSR-3 Logger interface instead. According to Dependency Inversion principle SOLID, we should depend upon abstractions rather than concretions. PSR-3 Logger interface provides a perfect abstraction for our case.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class User&#13;
{&#13;
    private $logger;&#13;
&#13;
    public function __construct(PsrLogLoggerInterface $logger)&#13;
    {&#13;
        $this-&gt;logger = $logger;&#13;
    }&#13;
&#13;
    public function login($username, $password)&#13;
    {&#13;
        if ($this-&gt;validUsernameAndPassword($username, $password)) {&#13;
            $this-&gt;logger-&gt;info('login');&#13;
        }&#13;
    }&#13;
&#13;
    private function validUsernameAndPassword($username, $password)&#13;
    {&#13;
    // ... ...&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    By changing a few lines of our code, we have replaced our custom logger with PsrLogLoggerInterface. Now our code is highly reusable. We can use, switch to, or change to, any third-party logger library that is compliant with with PSR-3 Logger interface.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;PSR-7&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    HTTP messages are essential for web applications. Every action a user takes is a combination of a HTTP request and HTTP response. PSR-7 is the latest accepted standard. It provides abstractions around HTTP messages and the elements composing them. It will have a huge impact on projects that implement details of HTTP messages, since HTTP is a rather complex subject and most of vendors have their own implementation, it is a lot of refactoring for vendors to adapt PSR-7.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As a user of HTTP messages, we can now deal with HTTP messages universally thanks to PSR-7. Similar to PSR-3, PSR-7 makes our lives much easier to build a reusable codebase.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. PSR Specifications&lt;/h6&gt;&#13;
                &lt;p&gt;&#13;
                    We have summarized each PSR briefly and you should now have an understanding of what each PSR is for.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    You should refer to the official page whenever you need detailed specifications of each PSR.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;PSR-1: &lt;a href="http://www.php-fig.org/psr/psr-1/"&gt;http://www.php-fig.org/psr/psr-1/&lt;/a&gt;&lt;/li&gt;&#13;
                    &lt;li&gt;PSR-2: &lt;a href="http://www.php-fig.org/psr/psr-2/"&gt;http://www.php-fig.org/psr/psr-2/&lt;/a&gt;&lt;/li&gt;&#13;
                    &lt;li&gt;PSR-3: &lt;a href="http://www.php-fig.org/psr/psr-3/"&gt;http://www.php-fig.org/psr/psr-3/&lt;/a&gt;&lt;/li&gt;&#13;
                    &lt;li&gt;PSR-4: &lt;a href="http://www.php-fig.org/psr/psr-4/"&gt;http://www.php-fig.org/psr/psr-4/&lt;/a&gt;&lt;/li&gt;&#13;
                    &lt;li&gt;PSR-7: &lt;a href="http://www.php-fig.org/psr/psr-7/"&gt;http://www.php-fig.org/psr/psr-7/&lt;/a&gt;&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;h6 id="sec5"&gt;5. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt; and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    Did we miss out anything? Do leave a comment below to let us know.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
</description><pubDate>Mon, 05 Feb 2018 13:19:29 +0000</pubDate></item><item><title>Modern PHP Developer - Composer</title><link>https://www.startutorial.com/articles/view/modern-php-developer-composer</link><guid>https://www.startutorial.com/articles/view/modern-php-developer-composer<isPermaLink>true</isPermaLink></guid><description>                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Package Manager&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Composer vs PEAR&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Install Composer&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;Use Composer&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec5"&gt;Power of community&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec6"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Package Manager&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In general, a block of code forms a method, a group of methods forms a class and a set of classes form a package.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A reusable package can be dropped into any project and be used without any need to add functionality to it.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A package exposes APIs for clients to achieve a single goal.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Packages help our applications achieve DRY (Don't Repeat Yourself), a principle of software development, which reduces repetition of information of all kinds.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In most cases, packages have dependencies. When "Package A" requires "Package B" in order to work, we say "Package A" depends on "Package B". It is quite common to see that a package has a chain of dependencies("Package A" depends on "Package B", "Package B" depends on "Package C", the list goes on).&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Imagine there is no such thing as a package manager. What would we need to do in order to get "Package A", which has a dependency of "Package B" to work? First we download source code of "Package A", then discover it depends on "Package B", so we try our best to find source code of "Package B". It might still not work, because we also need to make sure that we download the correct version of "Package B". The story can go on and on. We are only talking about one single dependency here; it would soon turn to be a nightmare if "Package A" has multiple dependencies or there is a chain of dependencies.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We do need a package manager, a package manager that can solve all of these dependency headaches for us.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;Composer vs. PEAR&lt;/h6&gt;&#13;
&#13;
                &lt;strong&gt;PEAR&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                Prior to Composer, there was something called PEAR. If you started with PHP early on, you may be aware of PEAR, as it has been in existence since 1999. PEAR is made for the purpose of promoting reusable packages, similar to Composer. However, it has been discouraged by developers due to the following reasons:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&#13;
                        Unlike Composer, PEAR is a system-wide package manager. When you have multiple projects, which share the same dependencies, but each has different versions, this approach causes a lot of confusion and frustration.&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        A certain number of up-votes is required in order to have your code accepted into PEAR's repository. This discouragement slows down growth of its repository. At the end of day, developers want to write code, not promote code.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;strong&gt;Composer&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Composer is an application-level package manager for PHP. It is inspired by NodeJs's NPM and Ruby's Bundler, and is currently the recognized package manager by the community.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The Composer ecosystem consists of two parts: the Composer, which is the command-line utility for installing packages, and the Packagist, the default package repository.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    An application-level package manager means it manages dependencies on a per project basis. This makes managing multiple projects easy and keeps your machine clean as it only downloads packages to your project directory.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Everyone is welcome to submit their packages to Packagist. Unlike PEAR, there is no need to get up-votes whatsoever. You do, however, get starts if people like your packages.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;strong&gt;Packagist&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As mentioned earlier, Packagist(packagist.org) is the default package repository for Composer. As of the time of this writing, September 2015, 69,568 packages are available on Packagist. Next time you need a PHP package, instead of building one from scratch on your own, there is a good chance you can find it on Packagist. As a developer, it is recommended you leverage the power of Packagist as it will save you countless hours and energy.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now, it's time to get our hands dirty.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec3"&gt;Install Composer&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We will assume you are a Mac user.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    There are two scopes when installing Composer: local scope and global scope. From professional experience, we suggest installing Composer globally on your system. After all, it is very likely we will use Composer to manage dependency for every PHP project. Global installation saves us a lot of hassle.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;strong&gt;Global Installation&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;Run commands below from your Terminal to install Composer globally:&lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
    curl -sS https://getcomposer.org/installer | php&#13;
&#13;
    mv composer.phar /usr/local/bin/composer&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you encounter any errors related to permissions, run commands above in sudo mode (append sudo to each command)&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;strong&gt;Local Installation&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Run commands below from your project root directory to install Composer locally:&#13;
                &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
curl -sS https://getcomposer.org/installer | php -- --filename=composer&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    For a more detailed installation guide on Composer, check out: https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;strong&gt;Verification&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    To verify if Composer is installed properly, run command below from the directory Composer is installed (Anywhere if Composer is installed globally).&#13;
                &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
composer about&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you see an output similar to the one below, you are ready to go.&#13;
                &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
Composer - Package Management for PHP&#13;
See https://getcomposer.org/ for more information.&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;Use Composer&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Composer is now ready to use. Let's demonstrate its usage through a simple example:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Imagine we have completed an awesome project and we want to generate simulated data, for example, people's names and addresses, to show our client. It would be cool if the data is random and yet makes sense, so the demo would look real. One solution would be to type some fake names and addresses, store them in an array, then pick entries out of the array randomly using array_rand. As you have probably realized, this solution sounds tedious and impractical. What happens if we need hundreds of users' data? We need a savior.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    It turns out there is a package on Packagist, which does exactly what we need. The best part is that it is even called Faker.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's install Faker using Composer.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    From our project root folder, run command:&#13;
                &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
composer require fzaninotto/faker&#13;
&lt;/script&gt;&#13;
                &lt;p&gt;&#13;
                    It will take Composer a few seconds to download the required files. Under the hood, Composer downloads the zip file of Faker from Github. Besides downloading the required package, Composer will also create some internal files, which we will look into later.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now take a look at our project directory and you should be able to discover some newly created folders and files as shown below:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;composer.json&lt;/li&gt;&#13;
                    &lt;li&gt;composer.lock&lt;/li&gt;&#13;
                    &lt;li&gt;vendor&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;strong&gt;composer.json&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This file describes the dependencies of your project. It is a simple JSON file and shows you what packages are installed in your project.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Whenever you run &lt;code&gt;composer require&lt;/code&gt; from command line, composer.json and composer.lock will be automatically updated to reflect package change. Conversely, if you add a package to composer.json file,&#13;
                    you run &lt;code&gt;composer install&lt;/code&gt; to download the new package. If you want to update all packages' versions to the latest specified by their version constraints, you can run&#13;
                    &lt;code&gt;composer update&lt;/code&gt;.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    There are three basic commands of Composer:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;strong&gt;composer require&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This command is used to add an individual package to the dependencies. Whenever we need a new package, we can just run it. It is convenient because we do not have to touch the composer.json file at all.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Another usage of this command is to update an existing package's version.&#13;
                    For example, we have installed the latest version(1.4.0) of Faker using&#13;
                    &lt;code&gt;composer require fzaninotto/faker &lt;/code&gt; as Composer fetchesthe latest version of a package if we do not specify its version constraint. Since our application is incompatible with 1.4.0, we need to install 1.2.0 in order to run&#13;
                    &lt;code&gt;composer require fzaninotto/faker:1.2 0 &lt;/code&gt;.&#13;
                    It will download a specific package and update all relevant Composer files accordingly.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;strong&gt;composer install&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This command first looks for composer.lock file, if it is present, exact version of the packages defined, will be installed and composer.son will then be ignored. If it is not present, the command will check packages defined in the composer.json file and download the latest versions of the packages that match the supplied version constraints. Can you spot the difference? When composer.lock is used, exact versions are downloaded, whereas using composer.json, Composer will always attempt to retrieve the latest version of a package that matches the supplied version constraint. When version constraint is defined as an exact number, both actions have the same result. However this is rarely the case.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This command is used when we begin a new project - we define a list of dependencies and run this command to get all packages installed. Or, when kick-start someone else's project, we check out their code from Github and run this command to get all dependencies installed.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In some deployment strategies, we run this command in production to install the application after pulling its source code from repository.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;strong&gt;composer update&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This command only reads from composer.json file which is different from composer install . It updates existing packages to the latest versions that match supplied version constraints defined in composer.json. Meanwhile, it downloads any new packages added to composer.json file.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We can use this command to update existing packages' versions,&#13;
                    similar to &lt;code&gt;composer require&lt;/code&gt;.&#13;
                    The difference is that &lt;code&gt;composer require&lt;/code&gt; does not require us to touch the composer.json file manually, it feels more intuitive.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The fact that this command only reads from composer.json brings up a common pitfall, which is running this on production. We should never run composer update in production. Here's why:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If your application is working well with Faker 1.2.0 on your local development environment,&#13;
                    you push your code to production and run &lt;code&gt;composer update&lt;/code&gt;.&#13;
                    Without your knowledge, the latest version of Faker has already been updated to 1.4.0, so Composer downloads version 1.4.0 of Faker in production, because you have defined its version constraint as 'fzaninotto/faker: 1.*' in composer.json. As a result, your production is now using a different package from your development. This is not the intended outcome.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We recommend deploying composer.lock along with compose.json and running &lt;code&gt;composer install&lt;/code&gt; in production. This will ensure your production has the same packages as your development.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;strong&gt;composer.lock&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    While composer.json file lets us define packages we need using versions constraints, composer.lock tracks exact versions of packages installed in our project. In other words, it stores the current state of our project. This is a very important point to remember.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The fact that &lt;code&gt;composer install&lt;/code&gt; reads first from composer.lock, makes it a much safer command to use. Here's why:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you delete &lt;strong&gt;vendor&lt;/strong&gt; completely from the project,&#13;
                    this will remove all packages Composer downloaded. Now run &lt;code&gt;composer install&lt;/code&gt; again and it will obtain the exact versions of packages as it previously did.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This brings up our next point. If we are using a version control system such as Git, should we commit composer.lock?&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The answer is "It Depends". Most of time we want to make sure everyone is sharing identical source code at anytime. So we will commit composer.lock. This is very common since most of us work with a team. The rare case of not committing composer.lock is when we develop a package(library), because users rarely need to run &lt;code&gt;composer install&lt;/code&gt; in our package.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Composer gives us a lot of flexibility in using its commands, however there are a couple of rules we try to follow to prevent liability.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;code&gt;composer install&lt;/code&gt; is our friend - use it in production for deployment.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A fair standard Composer workflow:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;ul&gt;&#13;
&#13;
&#13;
                    &lt;li&gt;Defined some dependencies in composer.json: run &lt;code&gt;composer install&lt;/code&gt;&lt;/li&gt;&#13;
                    &lt;li&gt;Need an individual package: run &lt;code&gt;composer require some/package&lt;/code&gt;&lt;/li&gt;&#13;
                    &lt;li&gt;Need multiple packages: define them in composer.json file and run &lt;code&gt;composer update&lt;/code&gt;&lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        Want to test out one single newly released package:&#13;
                        run &lt;code&gt;composer require some/package:new-version&lt;/code&gt;&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        Ready to test out all the latest versions of packages released:&#13;
                        run &lt;code&gt;composer update&lt;/code&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;strong&gt;Autoloading&lt;/strong&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    You have probably used a lot of &lt;code&gt;include/require&lt;/code&gt; statements. The problem with These statements is that, they make our code cluttered. And the worst part is, whenever we update our directory structure, we end up doing a lot of find&amp;replace work.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                The solution is autoloading. It allows you to define paths to search for classes so you do not have to do it manually with &lt;code&gt;include/require&lt;/code&gt;. But of cause, we should keep in mind that under the hood, autoloading is still using &lt;code&gt;include/require&lt;/code&gt;.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now, let's jump back to our awesome project. There is one place we have not really explored yet, and that is the vendor directory created by Composer. By default, Composer downloads all packages to this directory.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Composer also generates a vendor/autoload.php file, which provides autoloading to us for free, making it really easy to use vendor code.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In our case, we want to use Faker so we can simply include the below file and Faker will be autoloaded.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
require __DIR__ . '/vendor/autoload.php';&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now we can just start using Faker.&#13;
                &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
$faker = Faker\Factory::create();&#13;
&#13;
echo $faker-&gt;name;&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec5"&gt;Power of community&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    You should now have a fair understanding of Composer. Start using it to manage your project's dependencies. We guarantee it will make your and your co-workers' lives much easier. Next time your project needs something, start looking for them on Packagist. Embrace the power of community!&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec6"&gt;The end&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Mon, 05 Feb 2018 13:10:03 +0000</pubDate></item><item><title>Understanding Design Patterns - Facade</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-facade</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-facade<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher- level interface that makes the subsystem easier to use.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As a software developer, one main task we all have to do is deployment.&#13;
                    Similar to all of us, when Eric was just starting his career as a developer,&#13;
                    he was doing all the deployment jobs manually.&#13;
                    He was using a pretty standard way to do this: set server to offline mode, transfer source code files,&#13;
                    update the database’s schema, and set server back online:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$server-&gt;offline();&#13;
$fileSystem-&gt;transferFiles();&#13;
$database-&gt;updateSchema();&#13;
$server-&gt;online();&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This seemed like the ideal way to do it; the process was easy and straightforward. However, as more and more procedures were being introduced, human errors started happening. New procedures such as running tests before transferring files became more frequent. There was one time when his colleague saw Eric rushing back into the office after he had logged out of work for the day. They asked, “Hey Eric! What's the rush?" Eric replied without breaking his stride, “I forgot to update the database before setting the server back online!” As we all know, human errors are inevitable, but they can be minimized. We realize we need a better solution.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    What if we are able to encapsulate all the procedures into one simple method? That is so we will not have to worry about forgetting any step. To update the procedures, we just need to update on place. In this case, we can use the Facade Pattern.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let us see how it looks in code:&#13;
                &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class DeployFacade&#13;
{&#13;
    private $server = null;&#13;
    private $fileSystem = null;&#13;
    private $database = null;&#13;
    public function  __construct(Server $server, FileSystem $fileSystem, Database $database)&#13;
    {&#13;
        $this-&gt;server = $server;&#13;
        $this-&gt;fileSystem = $fileSystem;&#13;
        $this-&gt;database = $database;&#13;
    }&#13;
&#13;
    public function deploy()&#13;
    {&#13;
        $this-&gt;server-&gt;offline();&#13;
        $this-&gt;transferFiles();&#13;
        $this-&gt;updateSchema();&#13;
        $this-&gt;online();&#13;
    }&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;Now every time Eric needs to do a deployment, he just has to do the following:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$deployFacade-&gt;deploy();&#13;
                &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
&#13;
                You may quickly recognize that in reality we are already using something similar to DeployFacade, &#13;
                that is the deployment script. It is an example of the Facade Pattern. &#13;
                In our example, by using Facade Pattern, it provides a unified interface (DeployFacade) to a set of &#13;
                interfaces (Server, FileSystem and Database) in a subsystem. Facade defines a higher level of interface &#13;
                that makes the subsystem easier to use. No more forgetting any step ever again.&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;&#13;
</description><pubDate>Sat, 03 Feb 2018 04:30:07 +0000</pubDate></item><item><title>Understanding Design Patterns - Adapter</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-adapter</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-adapter<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    converts the interface of a class into another interface the clients expect. Adapter lets class work together that couldn’t otherwise because of incompatible interfaces.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Today, there are 15 types of electrical outlet plugs in use worldwide.&#13;
                    When you travel from China to Singapore, you might find yourself in trouble if you&#13;
                    do not have a socket adapter. Marina, who was travelling to Singapore for a symposium,&#13;
                    was very upset when she realized that she cannot charge her phone and gadgets in her&#13;
                    hotel room because the plug and socket don't match. She went to the reception area&#13;
                    and asked the hotel staff if they have any adapters. The hotel staff was quite&#13;
                    courteous but they informed her that they don't and Marina would have to buy one from&#13;
                    the local hardware.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In Singapore, the outlet plugs in use are type G, whereas electronic devices from China are using the type A plugs. The type G socket interface is not compatible with a type A plug, which expects a type A socket interface. In this case we need to use a type G to type A socket adapter.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This is an example of the Adapter Pattern. Let us see how it looks like in code.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    First, we have a TypeAPlug class and a TypeGSocket class:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class TypeAPlug&#13;
{&#13;
    public function connect(TypeASocketInterface $socket)&#13;
    {&#13;
        $socket-&gt;connectTwoPins();&#13;
    }&#13;
}&#13;
&#13;
class TypeGSocket&#13;
{&#13;
    public function connectThreePins() {}&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As we can see, connect() method of TypeAPlug class expects a TypeASocketInterface type and it calls a method connectTwoPins() of TypeASocketInterface type. We need to create a type G socket interface to type A socket interface adapter. We will name it GtypeToAtypeSocketAdatper:&#13;
                &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class GtypeToAtypeSocketAdatper implements TypeASocketInterface&#13;
{&#13;
    private $typeGSocket = null;&#13;
    public function __construct(TypeGSocket $typeGSocket)&#13;
    {&#13;
        $this-&gt;typeGSocket = $typeGSocket;&#13;
    }&#13;
&#13;
    public function connectTwoPins()&#13;
    {&#13;
        // some algorithms to be used&#13;
        $this-&gt;connectThreePins();&#13;
    }&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                GtypeToAtypeSocketAdatper class implements TypeASocetInterface interface, and it accepts an TypeGSocket class when it is instantiated. The composition-favored technique used here is very similar to the one in the Decorator Pattern. The key difference is that the Decorator Pattern retains the class type of the class it wraps. But the Adapter Pattern changes the class type of the class it wraps to the one clients expects.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Finally, let us see how type G socket is adapter to type A socket and used by type A plug:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$typeAPlug = new TypeAPlug();&#13;
$typeGSocket = new TypeGSocket();&#13;
$gTypeToAtypeAdapter = new GtypeToAtypeSocketAdatper($typeGSocket);&#13;
$typeAPlug-&gt;connect($gTypeToAtypeAdapter);&#13;
                &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                In the Adapter Pattern, there are some components to help you get familiar with the pattern:&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;ul&gt;&#13;
                &lt;li&gt;&#13;
                    Adaptee: This is the class, that exists before the adapter class is introduced. In our case, it would be the TypeGSocket class.&#13;
                &lt;/li&gt;&#13;
&#13;
                &lt;li&gt;&#13;
                    Adapter: This is the class, that wraps an adaptee class and makes it compatible with what client class expects. This class decouples adaptee class from client class. In our case, it is the GtypeToAtypeSocketAdatper class.&#13;
                &lt;/li&gt;&#13;
&#13;
                &lt;li&gt;&#13;
                    Client: This is the class that makes requests to the Adapter and receives what it expects. It is not aware of existence of the adaptee class. In our case, it is the TypeAPlug class.&#13;
                &lt;/li&gt;&#13;
            &lt;/ul&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                In our example, the Adapter Pattern converts the interface of a class (TypeGSockt class) into another interface (TypeAPlugInterface interface) the clients (TypeAPlug) expect. The Adapter(GtypeToAtypeSocketAdatper) allows class to work together what couldn’t otherwise&#13;
                work because of incompatible interfaces.&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;&#13;
</description><pubDate>Sat, 03 Feb 2018 04:26:19 +0000</pubDate></item><item><title>Understanding Design Patterns - State</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-state</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-state<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    John works as a customer support representative in a popular telephone support company.&#13;
                    In a customer-service-oriented company, the company's priority is to make sure that the&#13;
                    customers are satisfied and happy. To improve the service, the company invested a lot of&#13;
                    money on improving the support representative’s service. Recent studies show that a support&#13;
                    representative’s emotions affect how they perform on the job. John himself admits that his&#13;
                    first few words when he answers the phone usually indicates the kind of mood he is in.&#13;
                    When he is in a happy mood, he would normally greet the customer with a jolly “Hi there!” or&#13;
                    “Hello, How can I help you?” When he is angry and in a dark mood, his answer would be a curt&#13;
                    “Hello” or “Yes?” If John is in a moderate mood, he would open the conversation with “Hi”&#13;
                    or a mellow “Hello.”&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's put the above information into code:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class SupportRep&#13;
{&#13;
    private $_state =  "happy";&#13;
    public function setState($state)&#13;
    {&#13;
        $this-&gt;_state = $state;&#13;
    }&#13;
&#13;
    public function sayHi()&#13;
    {&#13;
        if ($this-&gt;_state=='happy') {&#13;
            echo 'hi there!';&#13;
        } else if ($this-&gt;_state=='angry') {&#13;
            echo 'yes?';&#13;
        } else if ($this-&gt;_state=='moderate') {&#13;
            echo 'hi';&#13;
        }&#13;
    }&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The code above is pretty straightforward and can help us study the representative’s behavior. However, as research progresses and more information is introduced, the code may not be sufficient. Research show that a person’s mood will change depending on the number of calls&#13;
                    he's had and of course his current mood.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    When John picks up five to ten phone calls, his mood will change from “happy” to “moderate,” this is probably because he is getting tired or is getting stressed from the calls. If he gets more than 10 phone calls, his mood will change from “moderate” to “angry,” it is indeed quite taxing to be handling too many support calls.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let us rework our code to add additional logics:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class SupportRep&#13;
{&#13;
    private $_state =  null;&#13;
    public  $numOfCalls = 0;&#13;
    public function setState($state)&#13;
    {&#13;
        $this-&gt;_state = $state;&#13;
    }&#13;
&#13;
    public function sayHi()&#13;
    {&#13;
        if ($this-&gt;_state=='happy') {&#13;
            echo 'hi there!';&#13;
            if ($this-&gt;numOfCalls&gt;5&amp;&amp;$this-&gt;numOfCalls&lt;10) {&#13;
                $this-&gt;setState('moderate');&#13;
            }&#13;
            if ($this-&gt;numOfCalls&gt;10) {&#13;
                $this-&gt;setState('angry');&#13;
            }&#13;
        } else if ($this-&gt;_state=='angry') {&#13;
            echo 'yes?';&#13;
        } else if ($this-&gt;_state=='moderate') {&#13;
            echo 'hi';&#13;
            if ($this-&gt;numOfCalls&gt;10) {&#13;
                $this-&gt;setState('angry');&#13;
            }&#13;
        }&#13;
        $this-&gt;numOfCalls;&#13;
    }&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Do you see anything wrong with the code above? No, there is nothing wrong with it except that it is cluttered with those if-else statements. It does not even look object-oriented to us, and the worst part is that it clearly violates the single responsibility principle (SRP). There are multiple reasons for this class to change. When you have additional logics for either happy state, moderate state, or angry state. It introduces code modification and remember we are just talking about sayHi() function here. What happens when the mood-based conditions apply to&#13;
                every aspect of a sales representative?&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Its time for a change. In this case, we are ready to use the State Pattern. the State Pattern allows us to encapsulate the part that varies, which is the sayHi function. It varies depending on the representative’s mood.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                First, let us create a StateInterface, which all subsequent states have to implement:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
interface StateInterface&#13;
{&#13;
   public function sayHi();&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Then we will create three state's classes, and each implements its own logic:&#13;
            &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class AngryState implements StateInterface&#13;
{&#13;
    private $_supportRep = null;&#13;
    public function __construct(SupportRep $supportRep)&#13;
    {&#13;
        $this-&gt;_supportRep = $supportRep;&#13;
    }&#13;
    public function sayHi()&#13;
    {&#13;
        echo 'yes?';&#13;
    }&#13;
}&#13;
&#13;
class ModerateState implements StateInterface&#13;
{&#13;
    private $_supportRep = null;&#13;
    public function __construct(SupportRep $supportRep)&#13;
    {&#13;
        $this-&gt;_supportRep = $supportRep;&#13;
    }&#13;
    public function sayHi() {&#13;
        echo 'hi';&#13;
        if ($this-&gt;_supportRep-&gt;numOfCalls&gt;10) {&#13;
            $this-&gt;_supportRep-&gt;setState(new AngryState($this-&gt;_supportRep&#13;
        ));&#13;
        }&#13;
    }&#13;
}&#13;
&#13;
class HappyState implements StateInterface&#13;
{&#13;
    private $_supportRep = null;&#13;
    public function __construct(SupportRep $supportRep)&#13;
    {&#13;
        $this-&gt;_supportRep = $supportRep;&#13;
    }&#13;
&#13;
    public function sayHi()&#13;
    {&#13;
        echo 'hi there!';&#13;
        if ($this-&gt;_supportRep-&gt;numOfCalls&gt;5&amp;&amp;$this-&gt;_supportRep-&gt;numOfCalls&lt;10) {&#13;
        Rep));&#13;
    ));&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Finaly, we need to rework SupportRep class.&#13;
            &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class SupportRep&#13;
{&#13;
    private $_state =  null;&#13;
    public  $numOfCalls = 0;&#13;
    public function __construct()&#13;
    {&#13;
        $this-&gt;_state = new ModerateState($this);&#13;
    }&#13;
&#13;
    public function setState($state)&#13;
    {&#13;
        $this-&gt;_state = $state;&#13;
    }&#13;
&#13;
    public function sayHi()&#13;
    {&#13;
        $this-&gt;_state-&gt;sayHi();&#13;
        $this-&gt;numOfCalls++;&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
&#13;
            &lt;p&gt;&#13;
                As you can see, the sayHi() function of SupportRep class delegates its responsibility to state class. It no longer violates SRP. Three states classes are still able to change the main class’s state via composition.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Now SupportRep has become cleaner, and if any additional logic needs to be added, it can be done as an in individual state class. Additional functions of SupportRep can be delegated to states classes.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                In our example, the State Pattern Allows an object(Support Rep object) to alter its behavior (sayHi function in individual state class) when its internal state changes (changing between HappyState, ModerateState, and AngryState). The object will appear to change its class.&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;</description><pubDate>Sat, 03 Feb 2018 04:25:24 +0000</pubDate></item><item><title>Understanding Design Patterns - Decorator</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-decorator</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-decorator<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Coffee is a constant in almost everyone's day. The caffeine shot it gives to jump-start the day&#13;
                    is something that most people cannot do without. Waking up to the smell of coffee brewing in&#13;
                    the kitchen is enough to perk up anyone's day. The aroma, the taste, and the energy boost&#13;
                    you get after a cup of coffee has made this dark drink an indispensible part of our mornings.&#13;
                    No wonder why coffee shops like Starbucks and the Coffee Bean are doing so well in their business.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A cup of black coffee is served as a beverage without cream or milk, and it looks like this in code:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
interface Beverage&#13;
{&#13;
    public function getName();&#13;
}&#13;
&#13;
class Coffee implements Beverage&#13;
{&#13;
    public function getName()&#13;
    {&#13;
        return 'Coffee';&#13;
    }&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    However, black coffee is not really a popular choice because of its overpowering bitter taste. Most people prefer to have milk in their coffee; this not only subdues the strong flavor of the coffee but also gives a sweet mellow flavor to the drink.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    To create it in code, what we would normally do is use subclassing. Inheritance seems to be a natural choice:&#13;
                &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class CoffeeWithMilk extends Coffee&#13;
{&#13;
    public function getName()&#13;
    {&#13;
        return 'Coffee with milk';&#13;
    }&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Now that we've added milk to our coffee, we realize that its not the only add-on we put in our drink. Some people like sugar, some prefer cream and sugar and some want milk and sugar. What if we need to create all the possible varieties? Supposing cream, milk, and sugar are the&#13;
                three available condiments, then there are six possible ways to make a cup of coffee. For every coffee variant, we will need to create a subclass:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class CoffeeWithMilk extends Coffee {}&#13;
class CoffeeWithCream extends Coffee {}&#13;
class CoffeeWithSugar extends Coffee {}&#13;
class CoffeeWithMilkAndCream extends Coffee {}&#13;
class CoffeeWithMilkAndSugar extends Coffee {}&#13;
class CoffeeWithCreamAndSugar extends Coffee {}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                In reality, there are even more variants. Choices can be as simple as less milk or less sugar, but the impact of those variations need to be taken note of. Now when you think about the add-ons like cocoa powder, cinnamon and other flavors that can enhance coffee, this can be a maintenance nightmare.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                We will need a better solution. This is when the Decorator Pattern comes in handy. We will create decorator classes that adds condiments to the coffee objects. First, let us create a decorator class that adds milk to a coffee:&#13;
            &lt;/p&gt;&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class WithMilkDecorator implements Beverage&#13;
{&#13;
    private $_coffee = null;&#13;
&#13;
    public function __construct(Coffee $coffee)&#13;
    {&#13;
        $this-&gt;_coffee = $coffee;&#13;
    }&#13;
&#13;
    public function getName()&#13;
    {&#13;
        return $this-&gt;_coffee-&gt;getName().' with milk';&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
&#13;
            &lt;p&gt;&#13;
                Note that, the WithMilkDecorator class still implements Beverage interface as Coffee class does.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Let us also create two other decorators:&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class WithSugarDecorator implements Beverage&#13;
{&#13;
    private $_coffee = null;&#13;
    public function __construct(Coffee $coffee)&#13;
    {&#13;
        $this-&gt;_coffee = $coffee;&#13;
    }&#13;
&#13;
    public function getName()&#13;
    {&#13;
        return $this-&gt;_coffee-&gt;getName().' with sugar';&#13;
    }&#13;
}&#13;
&#13;
class WithCreamDecorator implements Beverage&#13;
{&#13;
    private $_coffee = null;&#13;
    public function __construct(Coffee $coffee)&#13;
    {&#13;
        $this-&gt;_coffee = $coffee;&#13;
    }&#13;
&#13;
    public function getName()&#13;
    {&#13;
        return $this-&gt;_coffee-&gt;getName().' with cream';&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Now, instead of having six subclasses of Coffee, we will have three decorators and they will achieve the same goal that we need. For example, to make a cup of coffee with milk and sugar:&#13;
            &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$coffee = new Coffee();&#13;
$coffeeWithMilk = new WithMilkDecorator($coffee);&#13;
$coffeeWithMilkAndSugar = new WithSugarDecorator($coffeeWithMilk);&#13;
echo $coffeeWithMilkAndSugar-&gt;getName();&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Clearly, by using the Decorator Pattern, we create less classes to maintain and avoid introducing bugs with more codes. What's more, Decorator Pattern adds additional feature to the wrapper class at run time, so it is flexible to add/remove features compared to inheritance via subclassing.&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
            &lt;p&gt;&#13;
                In our example, the Decorator Pattern attaches additional responsibilities (milk condiment, sugar condiment and cream condiment) to an object (Coffee object) dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;&#13;
</description><pubDate>Sat, 03 Feb 2018 04:24:14 +0000</pubDate></item><item><title>Understanding Design Patterns - Composite</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-composite</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-composite<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Agnes has been working at Walmart for more than a year; she started as an inventory assistant and has&#13;
                    recently been promoted as an inventory clerk. Agnes’s main job as an inventory clerk is to do daily&#13;
                    stock recording. On her third day on the job, Agnes was approached by the manager with a concern.&#13;
                    “Agnes, the inventory for the toy cars is inaccurate, not all boxes have the same number of cars&#13;
                    inside. It is because some toy cars are bigger than the others so less cars will fit in the box.”&#13;
                    After apologizing to the manager, Agnes went back to work. Being new to the job, she realized&#13;
                    that this job was harder than she thought, she had to figure out a way to record the boxes accurately.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Below is how Product class looks like:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Product&#13;
{&#13;
    private $_name = null;&#13;
    public function  __construct($name)&#13;
    {&#13;
        $this-&gt;_name = $name;&#13;
    }&#13;
&#13;
    public function getName()&#13;
    {&#13;
        echo $this-&gt;_name;&#13;
    }&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Below is how Box class looks like:&#13;
                &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Box&#13;
{&#13;
   private $_products = array();&#13;
   public function addProduct($products)&#13;
   {&#13;
       $this-&gt;_products = $products;&#13;
   }&#13;
&#13;
   public function getProducts()&#13;
   {&#13;
       echo $this-&gt;_product;&#13;
   }&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;Below is how Agnes’s job looks like:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class InventoryClerk&#13;
{&#13;
    public function recordProducts(Box $box)&#13;
    {&#13;
        $products = $box-&gt;getProducts();&#13;
        foreach($products as $product) {&#13;
            $product-&gt;getName();&#13;
        }&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                The entire inventory process seems to be pretty straightforward; however,&#13;
                that is not the case. In most cases, a big box consists of a dozen of small boxes,&#13;
                and in some cases, a product is packaged with a smaller box. This is quite a task for Agnes,&#13;
                and it often takes more time than it should because she has to sort everything out,&#13;
                creating a different category for the boxes according to their content and the amount of products within.&#13;
                This makes her work more tedious that I should be.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                One possible solution to this problem is to place some conditions on the code. However, the packaging for the products may change in the future, and there is no way to tell what the actual contents of upcoming products will be. This makes the possible solution impractical and the codes difficult to maintain.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Agnes needs a better solution, a sustainable solution that is easy to maintain.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                This is when the Composite Pattern comes into place. There is a part-whole hierarchy of objects in our case. A box may contain a box or a product. We can make the InventoryClerk class to treat Product object and Box object uniformly using the Composite Pattern.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                In the Composite Pattern. there are four elements:&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;ul&gt;&#13;
                &lt;li&gt;&#13;
                    Component: It is the interface that has both Left and Composite to implement. This class&#13;
                    defines the abstract functions that the client uses. In our case, the function is getName().&#13;
                &lt;/li&gt;&#13;
&#13;
                &lt;li&gt;&#13;
                    Leaf: It is the class that has no child classes as its name implies. It implements Component interface as mentioned. In our case, Leaf is our Product class.&#13;
                &lt;/li&gt;&#13;
&#13;
                &lt;li&gt;&#13;
                    Composite: It composites abstract Component classes. So it can composite concrete Product class, Composite class or both, besides implementing Component interface. Composite also provides functions for adding, removing, and getting child components.&#13;
                &lt;/li&gt;&#13;
&#13;
                &lt;li&gt;&#13;
                    Client: It treats both Leaf and Composite classes uniformly by calling the common function defined in Component class.&#13;
                &lt;/li&gt;&#13;
            &lt;/ul&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Let us rework our classes. First, we will need to create an interface ProductComponent:&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
interface ProductComponent&#13;
{&#13;
   public function getName();&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Rework Product class. It needs to implement ProductComponent interface:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Product implements ProductComponent&#13;
{&#13;
    private $_name = null;&#13;
&#13;
    public function  __construct($name)&#13;
    {&#13;
        $this-&gt;_name = $name;&#13;
    }&#13;
&#13;
    public function getName()&#13;
    {&#13;
        echo $this-&gt;_name;&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
&#13;
            &lt;p&gt;&#13;
                Rework Box class. Beside implementing ProductComponent interface, it needs to have functions for adding, removing, and getting ProductComponent:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Box implements ProductComponent&#13;
{&#13;
   private $_productComponents = array();&#13;
   public function getName()&#13;
   {&#13;
        $productComponents = $this-&gt;getProductComponents();&#13;
        foreach($productComponents as $productComponent) {&#13;
             $productComponent-&gt;getName();&#13;
        }&#13;
   }&#13;
&#13;
   public function addProductComponent(ProductComponent $productComponent)&#13;
   {&#13;
        $this-&gt;_productComponents[] = $productComponent;&#13;
   }&#13;
&#13;
   public function removeProductComponent($i)&#13;
   {&#13;
        unset($this-&gt;_productComponents[$i]);&#13;
   }&#13;
&#13;
   public function getProductComponents()&#13;
   {&#13;
        return $this-&gt;_productComponents;&#13;
   }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
        &lt;p&gt;&#13;
            Finally, rework InventoryClerk class; it has became very lean:&#13;
        &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class InventoryClerk&#13;
 {&#13;
    public function recordProducts(ProductComponent $productComponent)&#13;
    {&#13;
        $productComponent-&gt;getName();&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
&#13;
                Now that we have applied the Composite Pattern to our case, our code has become much easier to maintain, and it is flexible too. Regardless of how many boxes there are within a box or no matter if the boxes have varying sizes and content, our code will work.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Let us take as an example two toys products wrapped in a small box individually and then the two small boxes are placed into a big box:&#13;
            &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$productHelicopter = new Product('toy helicopter');&#13;
$productCar       = new Product('toy car');&#13;
$smallBoxForHelicopter = new Box();&#13;
$smallBoxForHelicopter-&gt;addProductComponent($productHelicopter);&#13;
$smallBoxForCar = new Box();&#13;
$smallBoxForCar-&gt;addProductComponent($productCar);&#13;
$bigBox = new Box();&#13;
$bigBox-&gt;addProductComponent($smallBoxForHelicopter);&#13;
$bigBox-&gt;addProductComponent($smallBoxForCar);&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    For the Inventory Clerk, to record the big box, it will be as easy as this:&#13;
                &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class InventoryClerk&#13;
{&#13;
    public function recordProducts(ProductComponent $productComponent)&#13;
    {&#13;
        $productComponent-&gt;getName();&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In our example, the Composite Pattern allows us to compose objects (Product objects and Box objects) into tree structures to represent part-whole hierarchies. Composite lets clients (InventoryClerk objects) treat individual objects (Product objects and Box objects) and compositions of objects uniformly (via ProductComponent abstraction).&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;&#13;
&#13;
</description><pubDate>Sat, 03 Feb 2018 04:23:20 +0000</pubDate></item><item><title>Understanding Design Patterns - Iterator</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-iterator</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-iterator<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As a store manager, Eric’s job includes checking in products from each department.&#13;
                    There are actually two departments in the store. One is called men's department,&#13;
                    which holds products for men, and the other one is called women's department for women's&#13;
                    products. Each department stores their products using different storage structures&#13;
                    (data structures).&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The Men's department stores products using array structure:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class MenDepartment&#13;
{&#13;
    private $_products = array();&#13;
    public function  getProducts()&#13;
    {&#13;
        return $this-&gt;_products;&#13;
    }&#13;
&#13;
    public function addProduct(Product $product)&#13;
    {&#13;
        $this-&gt;_products[] = $product;&#13;
    }&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The women's department stores products using SqlStack structure:&#13;
                &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class WomenDepartment&#13;
{&#13;
    private $_products;&#13;
&#13;
    public function __construct()&#13;
    {&#13;
        $this-&gt;_products = new SplStack();&#13;
    }&#13;
&#13;
    public function  getProducts()&#13;
    {&#13;
        return $this-&gt;_products;&#13;
    }&#13;
&#13;
    public function addProduct(Product $product)&#13;
    {&#13;
        $this-&gt;_products-&gt;push($product);&#13;
    }&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;So for Eric, the store manager, the code would look like this. Pay attention to function checkIn():&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class StoreManager&#13;
{&#13;
    private $_menDepartment;&#13;
    private $_womenDepartment;&#13;
    public function __construct(MenDepartment $menDepartment, WomenDepartm&#13;
ent $womenDepartment)&#13;
    {&#13;
        $this-&gt;_menDepartment = $menDepartment;&#13;
        $this-&gt;_womenDepartment = $womenDepartment;&#13;
    }&#13;
&#13;
    public function checkIn()&#13;
    {&#13;
       $menProducts = $this-&gt;_menDepartment-&gt;getProducts();&#13;
       foreach($menProducts as $menProduct) {&#13;
           echo $menProduct-&gt;getName();&#13;
       }&#13;
       $womenProducts = $this-&gt;_womenDepartment-&gt;getProducts();&#13;
       while (!$womenProducts-&gt;isEmpty()) {&#13;
           $womanProduct = $womenProducts-&gt;pop();&#13;
           echo $womanProduct-&gt;getName();&#13;
       }&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Depending on the data structure the department uses, we need to use different way to iterator the storage.&#13;
                This will quickly introduce a problem. Imagine if the women's department decides to use an array&#13;
                to store products too. We will not only need to update the WomenDepartment class,&#13;
                but we will also need to alter checkIn() method. This will apparently violate the single responsibility&#13;
                principle (SRP). This is because a class should have only one reason to change. Here the checkIn()&#13;
                method depends heavily on data structure that the two departments use. It has at least two reasons to change.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                What if we can hide the underlying data structure that a department uses to store product&#13;
                and provide a universal way to iterator products? This is when we will need the Iterator Pattern.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Let us rework our code base.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                First, we will need to create an interface called Iterator:&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
interface ProductIterator&#13;
{&#13;
   public function hasNext();&#13;
   public function next();&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                The Iterator interface defines two methods that the StoreManager will use to iterate the products.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Let us create a concrete iterator for MenDepartment class:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class MenDepartmentIterator implements ProductIterator&#13;
{&#13;
   private $_position = 0;&#13;
   private $_products = array();&#13;
   public function __construct($products)&#13;
   {&#13;
        $this-&gt;_products = $products;&#13;
   }&#13;
&#13;
   public function hasNext()&#13;
   {&#13;
        return ($this-&gt;_position &lt; count($this-&gt;_products));&#13;
   }&#13;
   public function next()&#13;
   {&#13;
        $product = $this-&gt;_products[$this-&gt;_position];&#13;
        $this-&gt;_position ++;&#13;
        return $product;&#13;
   }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                We need an internal pointer in MenDepartment to keep track of the current index.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Let us create a concrete iterator for WomenDepartment class:&#13;
            &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class WomenDepartmentIterator implements ProductIterator&#13;
{&#13;
   private $_products ;&#13;
   public function __construct($products)&#13;
   {&#13;
        $this-&gt;_products = $products;&#13;
   }&#13;
&#13;
   public function hasNext()&#13;
   {&#13;
        return !($this-&gt;_products-&gt;isEmpty());&#13;
   }&#13;
&#13;
   public function next()&#13;
   {&#13;
        $product = $this-&gt;_products-&gt;pop();&#13;
        return $product;&#13;
   }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
        &lt;p&gt;&#13;
            Now we need to create a new method (createIterator) for MenDepartment and WomenDepartment.&#13;
            What this method does is to instantiate a concrete iterator designed previously.&#13;
            So that we can get their iterator directly:&#13;
        &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class MenDepartment&#13;
{&#13;
    private $_products = array();&#13;
    public function  getProducts()&#13;
    {&#13;
        return $this-&gt;_products;&#13;
    }&#13;
&#13;
    public function addProduct(Product $product)&#13;
    {&#13;
        $this-&gt;_products[] = $product;&#13;
    }&#13;
&#13;
    public function createIterator()&#13;
    {&#13;
        return new MenDepartmentIterator($this-&gt;_products);&#13;
    }&#13;
}&#13;
&#13;
class WomenDepartment&#13;
{&#13;
    private $_products;&#13;
    public function __construct()&#13;
    {&#13;
        $this-&gt;_products = new SplStack();&#13;
    }&#13;
&#13;
    public function  getProducts()&#13;
    {&#13;
        return $this-&gt;_products;&#13;
    }&#13;
&#13;
    public function addProduct(Product $product)&#13;
    {&#13;
        $this-&gt;_products-&gt;push($product);&#13;
    }&#13;
&#13;
    public function createIterator()&#13;
    {&#13;
        return new WomenDepartmentIterator($this-&gt;_products);&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Lastly, let us see how StoreManager has changed. Rest all remain the same, the only place we need to change is checkIn() method, and we also need to add a facilitate method checkInByIterator() to make the code cleaner:&#13;
                &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class StoreManager&#13;
{&#13;
    private $_menDepartment;&#13;
    private $_womenDepartment;&#13;
&#13;
    public function __construct(MenDepartment $menDepartment, WomenDepartment $womenDepartment)&#13;
    {&#13;
        $this-&gt;_menDepartment = $menDepartment;&#13;
        $this-&gt;_womenDepartment = $womenDepartment;&#13;
    }&#13;
&#13;
    public function checkIn()&#13;
    {&#13;
        $menDepartmentIterator   = $this-&gt;_menDepartment-&gt;createIterator();&#13;
        $womenDepartmentIterator = $this-&gt;_womenDepartment-&gt;createIterator();&#13;
        $this-&gt;checkInByIterator($menDepartmentIterator);&#13;
        $this-&gt;checkInByIterator($womenDepartmentIterator);&#13;
    }&#13;
&#13;
    public function checkInByIterator(ProductIterator $productIterator)&#13;
    {&#13;
        while ($productIterator-&gt;hasNext()) {&#13;
            $product = $productIterator-&gt;next();&#13;
            echo $product-&gt;getName();&#13;
        }&#13;
    }&#13;
}&#13;
&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                As we can see now, StoreManager is anti-fragile. It does not concern the data structures a&#13;
                department uses to store products. The code is now easier to maintain.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                In our example, the Iterator Pattern provides a way to access the elements (products)&#13;
                of an aggregate object (MenDepartment and WomenDepartment objects) sequentially without&#13;
                exposing its underlying representations (Array or SqlStack).&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;</description><pubDate>Sat, 03 Feb 2018 04:22:21 +0000</pubDate></item><item><title>Understanding Design Patterns - Strategy</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-strategy</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-strategy<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Commuting is a part of our daily lives. Every day, when we leave our house for work,&#13;
                    we have to choose transportation. As commuters, we have a lot of options - taxi, bus,&#13;
                    or train - it really depends on our mood and the situation we are in. Like if you were&#13;
                    in a hurry because you woke up late, then you will probably take a taxi.&#13;
                    On another day, when you want a no-fuss seat and you have time to spare,&#13;
                    then a bus is a good choice. On days when we want to make sure we get to a&#13;
                    certain location on time without the hassle of getting stuck in traffic, we would take a train.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This is a perfect sample of the Strategy Pattern.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    A bus, a train, and a taxi are all modes of transportation but they of course vary in many ways.&#13;
                    They are different from one another in terms of cost, and they take different routes to get you&#13;
                    to your destination. They are the same because they are all ways for you to get to your destination,&#13;
                    although in varying length of travel time. They all belong to one family, which is transportation.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let us first create a Transportation interface:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
interface  Transportation&#13;
{&#13;
     function transport(Passenger $passenger);&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Create a Bus class that implement Transportation interface:&#13;
                &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Bus implements Transportation&#13;
{&#13;
     public function transport(Passenger $passenger)&#13;
     {&#13;
         echo 'Take you to destination via route A';&#13;
     }&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;Create a Train class that implement Transportation interface:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Train implements Transportation&#13;
{&#13;
    public function transport(Passenger $passenger)&#13;
    {&#13;
        echo 'Take you to destination via route B';&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Create a Taxi class that implement Transportation interface:&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Taxi implements Transportation&#13;
{&#13;
    public function transport(Passenger $passenger)&#13;
    {&#13;
        echo 'Take you to destination via route C';&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Lastly, we need to create a Passenger class, that represents us:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Passenger&#13;
{&#13;
    private $_transportation = null;&#13;
&#13;
    public function goToWork()&#13;
    {&#13;
        $this-&gt;_transportation-&gt;transport($this);&#13;
    }&#13;
&#13;
    public function chooseTransport(Transportation $transportation)&#13;
    {&#13;
        $this-&gt;_transportation = $transportation;&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Let us see, how Passenger uses different transportations in a context:&#13;
            &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$john   = new Passenger();&#13;
$bus    = new Bus();&#13;
$train  = new Train();&#13;
$taxi   = new Taxi();&#13;
// Take a bus&#13;
$john-&gt;chooseTransport($bus);&#13;
$john-&gt;goToWork();&#13;
// Take a train&#13;
$john-&gt;chooseTransport($train);&#13;
$john-&gt;goToWork();&#13;
// Take a taxi&#13;
$john-&gt;chooseTransport($taxi);&#13;
$john-&gt;goToWork();&#13;
&lt;/script&gt;&#13;
&#13;
        &lt;p&gt;&#13;
            Bus, Train and Taxi classes vary independently from Passenger class, because they all implement&#13;
            Transportation interface.&#13;
        &lt;/p&gt;&#13;
&#13;
        &lt;p&gt;&#13;
            In our example, by applying the Strategy Pattern, we defined a family (Transportation family) of algorithms&#13;
            (Bus, Train and Taxi), encapsulates each one (Passenger class is only aware ofTransportation interface),&#13;
            and makes them interchangeable (They implement common interface). Strategy lets the algorithm vary&#13;
            independently from clients (Passenger class) that use it.&#13;
        &lt;/p&gt;&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;</description><pubDate>Sat, 03 Feb 2018 04:21:01 +0000</pubDate></item><item><title>Understanding Design Patterns - Template Method</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-template-method</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-template-method<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Defines the skeleton of an algorithm in a method, deferring some steps to subclasses.&#13;
                    Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Managing the daily itinerary of company employees can be a time-consuming task.&#13;
                    It would be much easier if the daily tasks can be programmed to occur automatically using a program.&#13;
                    Mark has been working for Yahaa Inc for the past four years; he is a programmer,&#13;
                    and his daily routine is exclusive doing programming-related tasks. Elisa is a marketer for the same company;&#13;
                    like Mark, she has her daily routine set, and hers is exclusive doing marketing tasks.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    As a programmer, Mark's daily routine in the company looks like this:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Programmer&#13;
{&#13;
&#13;
    public function workRoutine()&#13;
    {&#13;
        $this-&gt;markAttendance();&#13;
        $this-&gt;doProgrammingTask();&#13;
        $this-&gt;reportDailyCompletion();&#13;
    }&#13;
&#13;
    public function markAttendance()&#13;
    {&#13;
        echo 'I am marking my attendance';&#13;
    }&#13;
&#13;
    public function doProgrammingTask()&#13;
    {&#13;
        echo 'doing programming task';&#13;
    }&#13;
&#13;
    public function reportDailyCompletion()&#13;
    {&#13;
        echo 'I am reporting my daily completion';&#13;
    }&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
               &lt;ul&gt;&#13;
                   &lt;li&gt;&#13;
                       When Mark the programmer enters the company, the first thing he has to do is to mark his attendance in the attendance tracking system; this makes sure that he will be paid for the day (markAttendance()).&#13;
                   &lt;/li&gt;&#13;
                   &lt;li&gt;&#13;
                       After that, he then proceeds to do his job according to his role (doingProgrammingTask()).&#13;
                   &lt;/li&gt;&#13;
                   &lt;li&gt;&#13;
                       Finally, he writes a detailed daily report about what he has completed for the day (reportDailyCompletion()).&#13;
                   &lt;/li&gt;&#13;
               &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now Elisa the marketer has almost the same routine as Mark except for step two. As a marketer, the second part of routine is to do marketing-related tasks.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We can easily spot the code duplication in those two classes above. Both programmer and marketer share some common procedures.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    How can we make the code better?&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We can obviously make it better if we can define some common procedures in the super class but still give flexibility to the subclasses to define its own function.&#13;
                    This is the time to apply the Template Method Pattern.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    It is time to rework our code. Let's define an abstract class with some predefined functions:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Programmer&#13;
{&#13;
    public function workRoutine()&#13;
    {&#13;
        $this-&gt;markAttendance();&#13;
        $this-&gt;doProgrammingTask();&#13;
        $this-&gt;reportDailyCompletion();&#13;
    }&#13;
&#13;
    public function markAttendance()&#13;
    {&#13;
        $this-&gt;doWork();&#13;
        $this-&gt;reportDailyCompletion();&#13;
    }&#13;
&#13;
    public function markAttendance()&#13;
    {&#13;
        echo 'I am marking my attendance';&#13;
    }&#13;
&#13;
    public function reportDailyCompletion()&#13;
    {&#13;
        echo 'I am reporting my daily completion';&#13;
    }&#13;
&#13;
    abstract public function doWork();&#13;
}&#13;
&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                This class looks very similar to either Programmer or Marketer class, except we have removed the&#13;
                function that varies between the two classes and replace it with an abstract class doWork().&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Now let us rework both Programmer and Marketer classes:&#13;
            &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Programmer extends Employee&#13;
{&#13;
    public function doWork()&#13;
    {&#13;
        $this-&gt;doProgrammingTask();&#13;
    }&#13;
&#13;
    public function doProgrammingTask()&#13;
    {&#13;
        echo 'doing programming task';&#13;
    }&#13;
}&#13;
&#13;
class Marketer extends Employee&#13;
{&#13;
    public function doWork()&#13;
    {&#13;
        $this-&gt;doMarketingTask();&#13;
    }&#13;
&#13;
    public function doMarketingTask()&#13;
    {&#13;
        echo 'doing marketing task';&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                As we can see, both Programmer and Marketer classes have become much cleaner and there is no more code duplication.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                In our example, we define the skeleton of an algorithm in a method (workRoutine() method in Employee class),&#13;
                deferring some steps (doWork()) to subclasses (Programmer and Marketer classes).&#13;
                Template method (doWork() method in Employee class) let subclasses (Programer and Marketer class)&#13;
                redefine certain steps (doWork()) of an algorithm without changing the algorithm's structure.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;&#13;
</description><pubDate>Sat, 03 Feb 2018 04:19:34 +0000</pubDate></item><item><title>Understanding Design Patterns - Command</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-command</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-command<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Battles are meant to be won, and no battle can be won without a good plan or strategy.&#13;
                    Most battles that are lost are those where the commander orders his men into the battlefield without&#13;
                    any plan or, worse, without the capacity to command his men while they are in battle.&#13;
                    The result is havoc with every man fighting for himself instead of the group fighting as a group&#13;
                    and protecting each other. A carefully laid out plan, with each man knowing his position and what&#13;
                    to do at the right time, is the perfect battle plan. Have you ever thought of how battlefield plans are made?&#13;
                    If we simulated it in our code, do you think it would be complicated or interesting? As it turns out,&#13;
                    it is quite interesting, and if programming was used in battle, it would be the simplest thing to win&#13;
                    one battle after another.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In this chapter, we will see how battle plans are made with programming using Command Pattern.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In a typical Command Pattern, there are five elements. They are command interface, client, receiver, invoker, and concrete command.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We will explain them in detail later in the chapter.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    But first, let us complete the code for our battle plan:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
interface Command&#13;
{&#13;
    public function execute();&#13;
}&#13;
&#13;
class Gunner&#13;
{&#13;
   public function fire()&#13;
   {&#13;
        echo 'Fire in the hole';&#13;
   }&#13;
}&#13;
&#13;
class GunnerFireCommand implements Command&#13;
{&#13;
    private $_gunner = null;&#13;
    public function _construct(Gunner $gunner)&#13;
    {&#13;
       $this-&gt;_gunner = $gunner;&#13;
    }&#13;
&#13;
    public function execute()&#13;
    {&#13;
           $this-&gt;_gunner-&gt;fire();&#13;
    }&#13;
}&#13;
&#13;
class BattlePlan&#13;
{&#13;
    public $commandsWithCodeNames = array();&#13;
    public function setCommand($codeName, Command $command)&#13;
    {&#13;
        $this-&gt;commandsWithCodeNames[$codeName] = $command;&#13;
    }&#13;
&#13;
    public function executeCommand($codeName)&#13;
    {&#13;
        $command = $this-&gt;commandsWithCodeNames[$codeName];&#13;
        $command-&gt;execute();&#13;
    }&#13;
}&#13;
&#13;
// Commander's code&#13;
$peter = new Gunner();&#13;
$gunnerFireCommand = new GunnerFireCommand($peter);&#13;
$planA = new BattlePlan();&#13;
$planA-&gt;setCommand('planA', $gunnerFireCommand);&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Now let us use as an example the four elements in the Command Pattern:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let us rework the code.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&#13;
                        Command interface: it defines a common method, so all concrete command classes have to implement it.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Client: it is responsible for creating concrete command objects and receiver objects.&#13;
                        In our battlefield example, the commander is the client.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Invoker: it contains concrete command objects and call the execute() method at some point of time.&#13;
                        Please note that it holds concrete command objects by its interface(Command interface),&#13;
                        it does not actually know the exact type of objects it holds (Programming to abstraction),&#13;
                        so only execute() method of concrete command objects is exposed to it. In our battlefield example,&#13;
                        the battle plan is the invoker.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Receiver: it performs the specific tasks. In our battlefield example, Gunner is the receiver.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        Concrete Command: this class implements the Command interface and implement the execute() method.&#13;
                        Its purpose is to encapsulate the request as an object. To accomplish this, it binds a set of&#13;
                        receiver’s actions together and exposes the execute()method to the outside. In our battlefield example,&#13;
                        GunnerFireCommand is a concrete command.&#13;
                    &lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In our battlefield example, by using Command Pattern, we encapsulate a request&#13;
                    (fire()method of Gunner class) as an object (GunnerFireCommand). It lets us&#13;
                    parameterize other objects with different requests, queue, or log requests&#13;
                    (commander is able to make different battle plans with different commands,&#13;
                    for example, he can make a command to request a sniper and a gunner to attack together).&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;&#13;
</description><pubDate>Sat, 03 Feb 2018 04:18:29 +0000</pubDate></item><item><title>Understanding Design Patterns - Observer</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-observer</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-observer<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Defines a one-to-many dependency between objects so that when on object changes state, all of its dependents are notified and updated automatically.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Mary just became a new Mom! Like all new mothers, she is very excited about her new baby boy, Nathan.&#13;
                    Life just turned very rewarding but also challenging for Mary. As a new mom she is experiencing&#13;
                    the joys and challenges of caring for a new born baby. The baby is a light sleeper and easily gets&#13;
                    disturbed by small noises grown-ups make. So to make sure the baby is well rested and happy, Mary&#13;
                    and her husband have decided to turn their guest room into a nursery. This is perfect for the baby&#13;
                    with a little sacrifice on Mary's end because she has to check on the baby several times at night to&#13;
                    make sure everything is fine.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This is how it looks like from the coding point of view:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$mary   = new Mother();&#13;
$nathan = new Son();&#13;
$time   = date('H');&#13;
// wake up at 1am , 3am and 5am&#13;
if ($time=='01' || $time=='03' || $time=='05') {&#13;
    $mary-&gt;wakeUp();&#13;
    if ($nathan-&gt;isCrying()) {&#13;
        $mary-&gt;comfortBaby();&#13;
    }&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The baby is doing fine in his new nursery, but her husband noticed that Mary is looking a little tired.&#13;
                    “Honey, why do you look so tired this morning?” he asked his wife. Mary explained that she has&#13;
                    to make several trips to the baby's room last night to make sure that the baby is fine.&#13;
                    Obviously, this nightly routine of getting up at odd hours to check on little Nathan is becoming&#13;
                    exhausting for Mary. She is losing sleep and feels tired in the morning. It will only be a matter&#13;
                    of time until Mary will be sleep lagged and too exhausted during the day to take care of the baby.&#13;
                    This can take all the fun out of having a new baby. She knows that she needs to find a way to improve&#13;
                    this because she can get stressed and even sick. Luckily, her good friend Rose came to visit and&#13;
                    introduced her to a tool called baby audio monitor. The audio monitor is placed inside the baby's room,&#13;
                    and the moment little Nathan cries or makes a fuss, the audio monitor gives out a sound to tell Mary&#13;
                    that her baby needs her. Mary was so happy with this new tool because instead of pro-actively waking&#13;
                    up to check on the baby, she can sleep soundly and only wake up to check on Nathan if the monitor&#13;
                    tells her she needs to. Without knowing, Mary has used the Observer Pattern here.&#13;
                    Let us see how it applies. With the help of the baby audio monitor,&#13;
                    Mary registered herself as an observer of the subject (Nathan). Whenever the subject’s&#13;
                    state changes (Nathan cries or makes any noise), the observer(Mary) is notified automatically.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let us rework the code.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    First, we need to create two interfaces. The Observable interface, which is the interface of the Subject,&#13;
                    and the Observer interface, which is the interface of Observer.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&#13;
                    Observable:&#13;
                &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
interface Observable&#13;
{&#13;
    public function  registerObserver(Observer $o);&#13;
    public function  removeObserver(Observer $o);&#13;
    public function  notifyObservers();&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;Observer:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
interface Observer&#13;
{&#13;
    public function update();&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Then we need to modify Son class to implement Observable interface:&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Son implements Observable&#13;
{&#13;
    private $_observers = array();&#13;
    private $_isCry = false;&#13;
    public function registerObserver(Observer $o)&#13;
    {&#13;
        $this-&gt;_observers[] = $o;&#13;
    }&#13;
&#13;
    public function removeObserver(Observer $o)&#13;
    {&#13;
        foreach($this-&gt;_observers as $index=&gt;$value) {&#13;
            if ($value==$o) {&#13;
                unset($this-&gt;_observers[$index]);&#13;
            }&#13;
        }&#13;
    }&#13;
&#13;
    public function notifyObservers()&#13;
    {&#13;
        foreach($this-&gt;_observers as $observer) {&#13;
            $this-&gt;_observer-&gt;update();&#13;
        }&#13;
    }&#13;
&#13;
    public function cry()&#13;
    {&#13;
        $this-&gt;_isCry = true;&#13;
        $this-&gt;notifyObservers();&#13;
    }&#13;
&#13;
    public function isCry()&#13;
    {&#13;
        return $this-&gt;_isCry;&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                And Mother class needs to implement Observer interface:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Mother implements Observer&#13;
{&#13;
    public function update()&#13;
    {&#13;
        $this-&gt;wakeUp();&#13;
        $this-&gt;comfortBaby();&#13;
    }&#13;
&#13;
    public function wakeUp()&#13;
    {&#13;
        echo 'Wake up at once!';&#13;
    }&#13;
&#13;
    public function comfortBaby()&#13;
    {&#13;
        echo 'Baby do not cry.';&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Second, let us register Mary as an observer of Nathan at run time.&#13;
            &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$mary   = new Mother();&#13;
$nathan = new Son();&#13;
$nathan-&gt;registerObserver($mary);&#13;
&lt;/script&gt;&#13;
&#13;
        &lt;p&gt;&#13;
            With the help of the Observer Pattern, Mary has improved her daily routine and is now&#13;
            enjoying mommy life more. Some nights, she does not even have to wake up at all.&#13;
            As Nathan grows up, Mary will certainly no longer need to use the baby audio monitor.&#13;
            That is when she can remove herself as an observer of her son:&#13;
        &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$nathan-&gt;removeObserver($mary);&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;</description><pubDate>Sat, 03 Feb 2018 04:17:26 +0000</pubDate></item><item><title>Understanding Design Patterns - Singleton</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-singleton</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-singleton<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Ensures a class has only one instance, and provides a global point of access of it.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The health clinic has recently offered free medicines if you come in for a checkup.&#13;
                    The promotional stint is working so well, and it is just a matter of time before the&#13;
                    front staff will have more patients than they can handle. Everyone was so busy that instead of having an&#13;
                    organized waiting room, it was a total chaos. After several days of patients flooding in the receptionist,&#13;
                    Anne was frustrated and stressed, she went into the the clinic head's office and blurted,&#13;
                    "We need to organize the patients, or we are going to go down the drain".&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The head of the clinic called a meeting and asked the staff for suggestions,&#13;
                    and they came up with the idea of a ticketing system.&#13;
                    The aim was to get the patients organized so that it can ease the front staff's task&#13;
                    from doing manual registration.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let us see how we can help.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Before we do any code design, we need to know the condition and capability of the the health clinic.&#13;
                    The clinic has only one physical printer.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We could design our TicketPrinter class similar to:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class TicketPrinter&#13;
{&#13;
    public $isPaperOut;&#13;
    public function __construct()&#13;
    {&#13;
        $this-&gt;isPaperOut = true;&#13;
    }&#13;
&#13;
    public function printTicket()&#13;
    {&#13;
        if ($this-&gt;isPaperOut) {&#13;
            // load more papers into paper&#13;
            $this-&gt;loadMorePapers();&#13;
            $this-&gt;isPaperOut = false;&#13;
        } else {&#13;
            // deduct papers from printer&#13;
            $this-&gt;minusPaper();&#13;
            echo 'print queue number';&#13;
        }&#13;
    }&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The &lt;code&gt;printerTicket()&lt;/code&gt; method will have to check the paper’s status every time it does the print job.&#13;
                    If it runs out of paper, it should automatically load more (let's assume that is possible).&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Looks like we need to check the ink’s status too. So let us add that also:&#13;
                &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class TicketPrinter {&#13;
    public $isPaperOut;&#13;
    public $isInkOut;&#13;
    public function __construct()&#13;
    {&#13;
        $this-&gt;isPaperOut = true;&#13;
        $this-&gt;isInkOut = true;&#13;
    }&#13;
&#13;
    public function printTicket()&#13;
    {&#13;
        if ($this-&gt;isPaperOut) {&#13;
            // load more papers into paper&#13;
            $this-&gt;loadMorePapers();&#13;
            $this-&gt;isPaperOut = false;&#13;
        } else if($this-&gt;isPaperOut) {&#13;
            // load more papers into paper&#13;
            $this-&gt;loadMoreInk();&#13;
            $this-&gt;isInkOut = false;&#13;
        } else {&#13;
            // deduct papers from printer&#13;
            $this-&gt;minusPaper();&#13;
            // use ink&#13;
            $this-&gt;deductInk();&#13;
            echo 'print queue number';&#13;
        }&#13;
    }&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                It seems that we have a working TicketPrinter, but before we move on, let us examine&#13;
                the situation again. Since we have only one physical printer in the clinic,&#13;
                what will happen if by accident we create two instances of TicketPrinter class.&#13;
                Because they are using the same shared printer, it will surely cause a big problem.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                You may argue that we can always just create another instance of TicketPrinter&#13;
                but how can you make sure everyone follows that? So I propose we use the Singleton pattern&#13;
                in this case.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Let us rework TicketPrinter class a bit:&#13;
            &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class TicketPrinter&#13;
{&#13;
    private static $uniqueInstance=null;&#13;
    public $isPaperOut;&#13;
    public $isInkOut;&#13;
    private function __construct()&#13;
    {&#13;
        $this-&gt;isPaperOut = true;&#13;
        $this-&gt;isInkOut   = true;&#13;
    }&#13;
&#13;
    public static function getInstance()&#13;
    {&#13;
        if (self::$uniqueInstance==null) {&#13;
            self::$uniqueInstance = new TicketPrinter();&#13;
        }&#13;
        return self::$uniqueInstance;&#13;
    }&#13;
&#13;
    public function printTicket()&#13;
    {&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Because constructor of TicketPrinter has become private it can not be instantiated by constructor as normal.&#13;
                To obtain an instance of TicketPrinter, we instead do:&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$ticketPrinter = TicketPrinter::getInstance();&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
&#13;
                As you can see. Singleton Pattern has ensured that there is only one existence of TicketPrinter’s&#13;
                instance at any point of time across the system.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;</description><pubDate>Sat, 03 Feb 2018 04:16:24 +0000</pubDate></item><item><title>Understanding Design Patterns - Abstract Factory</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-abstract-factory</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-abstract-factory<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Business is bombing at Dragon Inc. and the CEO wants to franchise all overseas branches.&#13;
                    The first problem that comes to his attention is how they can ensure the quality of the products.&#13;
                    They do not want franchisees to cut costs and use low quality components.&#13;
                    Low quality toys would definitely destroy Dragon brand’s reputation.&#13;
                    So, the CEO wants to franchise the business,&#13;
                    but they still want to have factories located in each location to provide components.&#13;
                    Developers gather and start to brainstorm solutions.&#13;
                    There are three types of components used by toys; engines, wheels and rotor blades.&#13;
                    For example, a toy car needs an engine and four wheels,&#13;
                    while a toy helicopter uses a rotor blade and an engine.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Let us first create an abstract factory class, the back bone of all concrete factories.&#13;
                    Note that the abstract factory essentially consists of a group of factory methods:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
abstract class ComponentsFactory&#13;
{&#13;
    abstract function createEngine() ;&#13;
    abstract function createWheel() ;&#13;
    abstract function createRotorBlade() ;&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Then create a location specific factory (The concrete factory for creating concrete components).&#13;
                    Let us create one for New York:&#13;
                &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class NyComponentsFactory extends ComponentsFactory&#13;
{&#13;
&#13;
    public function createEngine()&#13;
    {&#13;
        return new NyEngine();&#13;
    }&#13;
&#13;
    public function createWheel()&#13;
    {&#13;
        return new NyWheel();&#13;
    }&#13;
&#13;
    public function createRotorBlade()&#13;
    {&#13;
        return new NyRotorBlade();&#13;
    }&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                The &lt;code&gt;Toy&lt;/code&gt; class also needs to be modified.&#13;
                Engines, wheels and rotor blades need to be clarified,&#13;
                and &lt;code&gt;prepare()&lt;/code&gt; function needs to be abstract&#13;
                (This method will be implemented by a concrete class.&#13;
                In the implementation, a child class uses its location specific&#13;
                &lt;code&gt;ComponentsFactory&lt;/code&gt; to create concrete components). Modify &lt;code&gt;Toy&lt;/code&gt; class:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
abstract class Toy {&#13;
    public $name    = '';&#13;
    public $price   = 0;&#13;
    public $engine  = null;&#13;
    public $wheels  = array();&#13;
    public $rotorBlade = null;&#13;
    abstract function prepare() ;&#13;
    public function package()&#13;
    {&#13;
        echo $this-&gt;name. ' is packaged';&#13;
    }&#13;
&#13;
    public function label()&#13;
    {&#13;
        echo $this-&gt;name . ' is priced at '.$this-&gt;price;&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Let's modify the &lt;code&gt;NyCar&lt;/code&gt; and &lt;code&gt;NyHelicopter&lt;/code&gt; classes to implement &lt;code&gt;prepare()&lt;/code&gt; method.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class NyCar extends Toy&#13;
{&#13;
    public $name  = 'NyCar';&#13;
    public $price = 30;&#13;
    public $componentsFactory = null;&#13;
    public function  __construct(ComponentsFactory $componentsFactory)&#13;
    {&#13;
        $this-&gt;componentsFactory = componentsFactory;&#13;
    }&#13;
&#13;
    public function prepare()&#13;
    {&#13;
        $this-&gt;engine   = $this-&gt;componentsFactory-&gt;createEngine();&#13;
        $this-&gt;wheels[] = $this-&gt;componentsFactory-&gt;createWheel();&#13;
        $this-&gt;wheels[] = $this-&gt;componentsFactory-&gt;createWheel();&#13;
        $this-&gt;wheels[] = $this-&gt;componentsFactory-&gt;createWheel();&#13;
        $this-&gt;wheels[] = $this-&gt;componentsFactory-&gt;createWheel();&#13;
    }&#13;
}&#13;
&#13;
class NyHelicopter extends Toy&#13;
{&#13;
    public $name  = 'NyCar';&#13;
    public $price = 30;&#13;
    public $componentsFactory = null;&#13;
&#13;
    public function  __construct(ComponentsFactory $componentsFactory)&#13;
    {&#13;
        $this-&gt;componentsFactory = componentsFactory;&#13;
    }&#13;
&#13;
    public function prepare()&#13;
    {&#13;
        $this-&gt;engine      = $this-&gt;componentsFactory-&gt;createEngine();&#13;
        $this-&gt;rotorBlade  = $this-&gt;componentsFactory-&gt;createRotorBlade();&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Lastly factory method of concrete &lt;code&gt;ToysFactory&lt;/code&gt; needs to be modified.&#13;
                This is where to added location specific &lt;code&gt;ComponensFactory&lt;/code&gt;.&#13;
                Let's complete the code for &lt;code&gt;NyToysFactory&lt;/code&gt;:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class NyToysFactory extends ToysFactory&#13;
{&#13;
    public function createToy($toyName)&#13;
    {&#13;
        $toy = null;&#13;
        $nyComponentsFactory = new NyComponentsFactory();&#13;
        if ('car'==$toyName) {&#13;
            $toy = new NyCar($nyComponentsFactory);&#13;
        } else if ('helicopter'==$toyName) {&#13;
            $toy = new NyHelicopter($nyComponentsFactory);&#13;
        }&#13;
        return $toy;&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Now each franchise will have their components supplied by a component factory, which is controlled by Dragon Inc. HQ.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Throughout the course, we've built a franchise framework, giving Dragon Inc.&#13;
                control and enough freedom for each franchise to do what they're good at.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;</description><pubDate>Sat, 03 Feb 2018 04:15:17 +0000</pubDate></item><item><title>Understanding Design Patterns - Factory Method</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-factory-method</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-factory-method<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate.&#13;
                    The Factory method lets a class defer instantiation to subclasses.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    With Simple Factory in place, developers are now enjoying their day at Dragon Inc.&#13;
                    Despite the thorough discussion of toys, we haven't really looked the toy classes yet.&#13;
                    &lt;code&gt;Toy&lt;/code&gt; is an abstract class with the functions &lt;code&gt;prepare()&lt;/code&gt;,&lt;code&gt;package()&lt;/code&gt;, and &lt;code&gt;label()&lt;/code&gt;.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
abstract class Toy&#13;
{&#13;
    public $name  = '';&#13;
    public $price  = 0;&#13;
&#13;
    public function prepare()&#13;
    {&#13;
        echo $this-&gt;name. ' is prepared';&#13;
    }&#13;
&#13;
    public function package()&#13;
    {&#13;
        echo $this-&gt;name. ' is packaged';&#13;
    }&#13;
&#13;
    public function label()&#13;
    {&#13;
        echo $this-&gt;name . ' is priced at '.$this-&gt;price;&#13;
    }&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The concrete class &lt;code&gt;Car&lt;/code&gt; and &lt;code&gt;Helicopter&lt;/code&gt; inherit from super class &lt;code&gt;Toy&lt;/code&gt;.&#13;
                    They are pretty straightforward.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Car:&lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Car extends Toy&#13;
{&#13;
    public $name  = 'Car';&#13;
    public $price = 20;&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Helicopter:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Helicopter extends Toy&#13;
{&#13;
    public $name  = 'Helicopter';&#13;
    public $price = 100;&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Back to Dragon Inc. The CEO walks in to the developers' office with a smile on his face,&#13;
                but we know there's bad news coming. The CEO happily announces that Dragon Inc.&#13;
                is going to open several factories in US. They'll be located in different States,&#13;
                and the first two factories will be in New York and California.&#13;
                All toys will be produced locally with their own properties,&#13;
                which means that for the same type of toy &lt;code&gt;Car&lt;/code&gt;, the ones produced in New York will be&#13;
                &lt;code&gt;NyCar&lt;/code&gt; and those from California will be &lt;code&gt;CaCar&lt;/code&gt;. Simple Factory will make this task a cinch for the&#13;
                development team. All they need to do is create a location specific &lt;code&gt;SimpleFactory&lt;/code&gt; class and a location&#13;
                specific &lt;code&gt;ToysFactory&lt;/code&gt; class. Simple Factory simplifies the task and makes the developers' job easy.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                For example, for New York we could do:&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class NySimpleFactory&#13;
{&#13;
&#13;
    public function createToy($toyName)&#13;
    {&#13;
        $toy = null;&#13;
        if ('car'==$toyName) {&#13;
            $toy = new NyCar();&#13;
        } else if ('helicopter'==$toyName) {&#13;
            $toy = new NyHelicopter();&#13;
        }&#13;
        return $toy;&#13;
    }&#13;
}&#13;
&#13;
class NyToysFactory&#13;
{&#13;
    public $simpleFactory;&#13;
&#13;
    public function __construct(SimpleFactory $simpleFactory)&#13;
    {&#13;
        $this-&gt;simpleFactory = $simpleFactory;&#13;
    }&#13;
&#13;
    public function produceToy($toyName)&#13;
    {&#13;
        $toy = null;&#13;
        $toy = $this-&gt;simpleFactory-&gt;createToy($toyName);&#13;
        $toy-&gt;prepare();&#13;
        $toy-&gt;package();&#13;
        $toy-&gt;label();&#13;
        return $toy;&#13;
    }&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                The developers finish the new code quickly and hand it over to the US factories.&#13;
                After two weeks, the phone starts ringing in the developers’ office because the New York factory&#13;
                was having production issues. It turns out that the &lt;code&gt;NyToysFactory&lt;/code&gt; class has been modified by developer of&#13;
                the remote branch because staff there do not want to do packaging and labeling work.&#13;
                They have modified &lt;code&gt;produceToy()&lt;/code&gt; function by removing &lt;code&gt;label()&lt;/code&gt; and&#13;
                &lt;code&gt;package()&lt;/code&gt; functions.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
&#13;
                It seems like Simple Factory won't work in this scenario.&#13;
                We don't want branches in US to be able to modify &lt;code&gt;produceToy()&lt;/code&gt; function.&#13;
                &lt;code&gt;produceToy()&lt;/code&gt; should consist of a set of standard procedures and the branches should only be responsible for&#13;
                creating location specific toys. What if they can create an abstract class?&#13;
                And the abstract class they created will have a concrete &lt;code&gt;produceToy()&lt;/code&gt; method which will implement a set&#13;
                of standard operating procedure that all branches have to follow.&#13;
                Inside the &lt;code&gt;produceToy()&lt;/code&gt;, it calls its own abstract method &lt;code&gt;createToy()&lt;/code&gt; to obtain a toy object.&#13;
                This way &lt;code&gt;createToy()&lt;/code&gt; is able to encapsulate object creation and, since it's abstract, it delegates the creation to its subclasses.&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
            &lt;p&gt;&#13;
                That sounds like exactly what they need in their case:&#13;
            &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
abstract class ToysFactory&#13;
{&#13;
    public function produceToy($toyName)&#13;
    {&#13;
        $toy = null;&#13;
        $toy = $this-&gt;createToy($toyName);&#13;
        $toy-&gt;prepare();&#13;
        $toy-&gt;package();&#13;
        $toy-&gt;label();&#13;
        return $toy;&#13;
    }&#13;
&#13;
    abstract public function createToy($toyName);&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Now in New York branch, all they need to do is to implement &lt;code&gt;createToy()&lt;/code&gt; method&#13;
                in the subclass:&#13;
            &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class NyToysFactory extends ToysFactory&#13;
{&#13;
&#13;
    public function createToy($toyName)&#13;
    {&#13;
        $toy = null;&#13;
        if ('car'==$toyName) {&#13;
            $toy = new NyCar();&#13;
        } else if ('helicopter'==$toyName) {&#13;
            $toy = new NyHelicopter();&#13;
        }&#13;
        return $toy;&#13;
    }&#13;
&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                For the factory in California, they have to create another subclass &lt;code&gt;CaToyFactory&lt;/code&gt; to produce toys locally:&#13;
            &lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class CaToysFactory extends ToysFactory&#13;
{&#13;
    public function createToy($toyName)&#13;
    {&#13;
        $toy = null;&#13;
        if ('car'==$toyName) {&#13;
            $toy = new CaCar();&#13;
        } else if ('helicopter'==$toyName) {&#13;
            $toy = new CaHelicopter();&#13;
        }&#13;
        return $toy;&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In the code above, function &lt;code&gt;createToy()&lt;/code&gt; in &lt;code&gt;ToysFactory&lt;/code&gt; class is called factory method.&#13;
                    Factory Method pattern defines an interface(createToy) for creating an object.&#13;
                    But it delegates the actual creation to subclasses(&lt;code&gt;NyToysFactory&lt;/code&gt; and &lt;code&gt;CaToyFactory&lt;/code&gt;).&#13;
                    This way subclasses decide what object to create.&#13;
                &lt;/p&gt;&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;</description><pubDate>Sat, 03 Feb 2018 04:12:57 +0000</pubDate></item><item><title>Understanding Design Patterns - Simple Factory</title><link>https://www.startutorial.com/articles/view/understanding-design-patterns-simple-factory</link><guid>https://www.startutorial.com/articles/view/understanding-design-patterns-simple-factory<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    This series has been written for developers new to software design patterns&#13;
                    and those who find software design patterns difficult to understand.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;Dragon Inc. is one of the top toy manufacturers in China.&#13;
                    In fact, they're a pioneer in toy manufacturing.&#13;
                    They started production at a time when few toys were being produced commercially.&#13;
                    Hence, they dominated the market and became the leader in the toy production industry.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Their &lt;code&gt;produceToy()&lt;/code&gt; function looked like below:&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class ToysFactory&#13;
{&#13;
        public function produceToy($toyName)&#13;
        {&#13;
            $toy = null;&#13;
            if ('car'==$toyName) {&#13;
                $toy = new Car();&#13;
            } else if ('helicopter'==$toyName) {&#13;
                $toy = new Helicopter();&#13;
            }&#13;
            $toy-&gt;prepare();&#13;
            $toy-&gt;package();&#13;
            $toy-&gt;label();&#13;
            return $toy;&#13;
        }&#13;
&#13;
}&#13;
               &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Initially they only manufactured toys "Car" and "Helicopter".&#13;
                    For this simple task the function worked well and everyone was happy.&#13;
                    But not long after that, a cool new toy, the "Jumping Frog" was introduced by the design team.&#13;
                    Jumping Frog looked cool and they knew it was going to sell really well,&#13;
                    it was time to change the &lt;code&gt;productToy()&lt;/code&gt; function:&#13;
                &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class ToysFactory&#13;
{&#13;
&#13;
    public function produceToy($toyName)&#13;
    {&#13;
            $toy = null;&#13;
            if ('car'==$toyName) {&#13;
                $toy = new Car();&#13;
            } else if ('helicopter'==$toyName) {&#13;
                $toy = new Helicopter();&#13;
            } else if ('jumpingFrog'==$toyName) {&#13;
                $toy = new JumpingFrog();&#13;
            }&#13;
            $toy-&gt;prepare();&#13;
            $toy-&gt;package();&#13;
            $toy-&gt;label();&#13;
            return $toy;&#13;
    }&#13;
&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                As the business grew, more and more toys came into production&#13;
                and the CEO was very happy with the business's financial growth.&#13;
                However, in the development team's office the nightmare was just beginning.&#13;
                The developers were tasked to modify the produceToy() function with the introduction of&#13;
                every new toy. It has violated the open/close principle.&#13;
                Which states "software entities (classes, modules, functions, etc.) should be open for extension,&#13;
                but closed for modification".&#13;
                Every new toy brought in modifications of the &lt;code&gt;produceToy()&lt;/code&gt; function.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                It was time for refactoring. Let's us take a look at the situation here.&#13;
                What was the real issue with &lt;code&gt;produceToy()&lt;/code&gt; function?&#13;
                Concrete classes were instantiated inside &lt;code&gt;ToysFactory&lt;/code&gt; and&#13;
                messed up the &lt;code&gt;produceToy()&lt;/code&gt; function. The &lt;code&gt;ToysFactory&lt;/code&gt; class was tied to&#13;
                the concrete classes of toys. That's the issue.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                First, let us create a class to encapsulate the concrete class instantiation.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class SimpleFactory&#13;
{&#13;
&#13;
    public function createToy($toyName)&#13;
    {&#13;
        $toy = null;&#13;
        if ('car'==$toyName) {&#13;
            $toy = new Car();&#13;
        } else if ('helicopter'==$toyName) {&#13;
            $toy = new Helicopter();&#13;
        }&#13;
        return $toy;&#13;
    }&#13;
&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Second, we'll use &lt;code&gt;SimpleFactory&lt;/code&gt; with our brand new class longer need to touch&#13;
                to create the desired toys:&#13;
            &lt;/p&gt;&#13;
&#13;
&#13;
            &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class ToysFactory&#13;
{&#13;
&#13;
    public $simpleFactory;&#13;
&#13;
    public function __construct(SimpleFactory $simpleFactory)&#13;
    {&#13;
        $this-&gt;simpleFactory = $simpleFactory;&#13;
    }&#13;
&#13;
    public function produceToy($toyName)&#13;
    {&#13;
        $toy = null;&#13;
        $toy = $this-&gt;simpleFactory-&gt;createToy($toyName);&#13;
        $toy-&gt;prepare();&#13;
        $toy-&gt;package();&#13;
        $toy-&gt;label();&#13;
        return $toy;&#13;
    }&#13;
&#13;
}&#13;
            &lt;/script&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                With our brand new class &lt;code&gt;SimpleFactory&lt;/code&gt;, things just became cleaner.&#13;
                The Developers no longer need to touch &lt;code&gt;SimpleFactory&lt;/code&gt; when a new toy was introduced,&#13;
                and they'll use &lt;code&gt;SimpleFactory&lt;/code&gt; to produce a new toy instead of using the former messy code.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Tha is the Simple Factory. It is not a real design pattern per se,&#13;
                but it's a useful technique that you can apply to your own needs.&#13;
                With Simple Factory, concrete class instantiation is encapsulated.&#13;
                It decouples the client code from the object creation code.&#13;
            &lt;/p&gt;&#13;
&#13;
            &lt;h6&gt;The end&lt;/h6&gt;&#13;
&#13;
            &lt;p&gt;&#13;
                Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                and help spread the word. We need your support to continue.&#13;
                &lt;br&gt;&#13;
                If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                know.&#13;
            &lt;/p&gt;&#13;
&#13;
</description><pubDate>Sat, 03 Feb 2018 04:00:58 +0000</pubDate></item><item><title>Data Structure and Algorithm - Shell Sort</title><link>https://www.startutorial.com/articles/view/data-structure-and-algorithm-shell-sort</link><guid>https://www.startutorial.com/articles/view/data-structure-and-algorithm-shell-sort<isPermaLink>true</isPermaLink></guid><description>&lt;blockquote&gt;In this tutorial, we will learn a simple sorting algorithm - Shell Sort.&lt;/blockquote&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Problem to Solve&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Pseudocode&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;PHP Implementation&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Problem to Solve&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Given a list of numbers as shown below, please sort them in ascending order.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
                    $numbers = [21,25,100,98,89,77];&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Requirements&lt;/strong&gt;:&lt;/p&gt;&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;You are required to use Shell Sort algorithm when sorting the numbers.&lt;/li&gt;&#13;
                    &lt;li&gt;You are required to implement the algorithm in PHP language.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Pseudocode&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Shell Sort is a generalisation of Insertion Sort.&#13;
                    Unlike Insertion Sort, instead of comparing contiguous items,&#13;
                    it breaks the master list into several sub-lists using an interval &lt;i&gt;i&lt;/i&gt; (which is known as the gap),&#13;
                    then sorts the sub-lists with Insertion Sort.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We repeat the steps above until the gap becomes 1,&#13;
                    then we essentially apply a standard Insertion Sort.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Apparently, the gap sequence plays an important role in this sort algorithm.&#13;
                    Unfortunately, there is no perfect gap sequence, so to speak. Different&#13;
                    researchers have come out a couple of different gap sequences, their performance&#13;
                    depends heavily on the input data size.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Some popular gap sequences:&lt;/p&gt;&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;Shell Sequence: FLOOR(N/2k)&lt;/li&gt;&#13;
                    &lt;li&gt;Pratt Sequence: 2p3q&lt;/li&gt;&#13;
                    &lt;li&gt;Knuth Sequence: (3k â€“ 1) / 2&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;We are using Shell Sequence in this tutorial.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;img src="https://www.startutorial.com/img/shell-sort.jpg" class="thumbnail"&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Pseudocode of Shell Sort algorithm can be written as follows:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
Caculate gap size ($gap)&#13;
&#13;
    WHILE $gap is greater than 0&#13;
&#13;
	    FOR each element of the list, that is $gap apart&#13;
&#13;
        	Extract the current item&#13;
&#13;
            Locate the position to insert&#13;
&#13;
            Insert the item to the position&#13;
&#13;
	    END FOR&#13;
&#13;
	    Calculate gap size ($gap)&#13;
&#13;
	END WHILE&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. PHP Implementation&lt;/h6&gt;&#13;
                &lt;p&gt;We need a FOR loop and a WHILE loop. We are using the FOR loop to iterate the master list and&#13;
                the WHILE loop to locate the position to insert the item. &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
$numbers = [21, 25, 100, 98, 89, 77];&#13;
&#13;
$gap  = floor(count($numbers)/2);&#13;
&#13;
while ($gap &gt; 0) {&#13;
&#13;
    for ($i = 0; $i &lt; count($numbers) - $gap; $i++) {&#13;
&#13;
        $extractItem = $numbers[$i + $gap];&#13;
&#13;
        $positionFound = $i + $gap;&#13;
&#13;
        while (($positionFound - $gap) &gt; 0 &amp;&amp; $extractItem &lt; $numbers[$positionFound - $gap]) {&#13;
&#13;
            $numbers[$positionFound] = $numbers[$positionFound - $gap];&#13;
&#13;
            $positionFound = $positionFound - $gap;&#13;
        }&#13;
&#13;
        $numbers[$positionFound] = $extractItem;&#13;
    }&#13;
&#13;
    $gap = floor($gap/2);&#13;
}&#13;
&#13;
print_r($numbers);&#13;
&#13;
// Output:&#13;
/*&#13;
Array&#13;
(&#13;
    [0] =&gt; 21&#13;
    [1] =&gt; 25&#13;
    [2] =&gt; 77&#13;
    [3] =&gt; 89&#13;
    [4] =&gt; 98&#13;
    [5] =&gt; 100&#13;
)&#13;
*/&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The implementation is similar to Insertion Sort, except that we are comparing&#13;
                    items that are $gap apart until the $gap values become 1. Then we perform a&#13;
                    standard Insertion Sort.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Mon, 14 Aug 2017 06:48:19 +0000</pubDate></item><item><title>Data Structure and Algorithm - Selection Sort</title><link>https://www.startutorial.com/articles/view/data-structure-and-algorithm-selection-sort</link><guid>https://www.startutorial.com/articles/view/data-structure-and-algorithm-selection-sort<isPermaLink>true</isPermaLink></guid><description>&lt;blockquote&gt;In this tutorial, we will learn a simple sorting algorithm - Selection Sort.&lt;/blockquote&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Problem to Solve&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Pseudocode&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;PHP Implementation&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Problem to Solve&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Given a list of numbers as shown below, please sort them in ascending order.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
                    $numbers = [21,25,100,98,89,77];&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Requirements&lt;/strong&gt;:&lt;/p&gt;&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;You are required to use Selection Sort algorithm when sorting the numbers.&lt;/li&gt;&#13;
                    &lt;li&gt;You are required to implement the algorithm in PHP language.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Pseudocode&lt;/h6&gt;&#13;
                &lt;p&gt;Selection Sort works by maintaining a sorted sub-list, finding the smallest item from&#13;
                    the master list and swap it to the last element of the sub-list until all items are&#13;
                    sorted.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;The sorted sub-list's length is increased by one, whereas the master list's length is&#13;
                    shrunk by one after each swap.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;img src="https://www.startutorial.com/img/selection-sort.jpg" class="thumbnail"&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Pseudocode of Selection Sort algorithm can be written as follows:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
FOR each element of the master list indexed by i&#13;
&#13;
    Set current element of master list as the sub-list[i] element&#13;
&#13;
    Find the smallest item from the master list (staring from i)&#13;
&#13;
    Swap it with the last element of sub-list&#13;
&#13;
END FOR&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. PHP Implementation&lt;/h6&gt;&#13;
                &lt;p&gt;We need an outer FOR loop to iterate through the master list and an inner FOR loop to&#13;
                    find the smallest item from the master list. &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
$masterList = [21, 25, 100, 98, 89, 77];&#13;
&#13;
$subList = [];&#13;
&#13;
for ($i = 0; $i &lt; count($masterList); $i++) {&#13;
&#13;
    $subList[$i] = $masterList[$i];&#13;
&#13;
    // Find the smallest item&#13;
    $smallestIndex = $i;&#13;
&#13;
    for ($j = $i; $j &lt; count($masterList); $j++) {&#13;
        if ($masterList[$j] &lt; $masterList[$smallestIndex]) {&#13;
            $smallestIndex = $j;&#13;
        }&#13;
    }&#13;
&#13;
    // Swap&#13;
    $tmp = $subList[count($subList) - 1];&#13;
    $subList[count($subList) - 1] = $masterList[$smallestIndex];&#13;
    $masterList[$smallestIndex] = $tmp;&#13;
}&#13;
&#13;
&#13;
print_r($subList);&#13;
&#13;
// Output:&#13;
/*&#13;
Array&#13;
(&#13;
    [0] =&gt; 21&#13;
    [1] =&gt; 25&#13;
    [2] =&gt; 77&#13;
    [3] =&gt; 89&#13;
    [4] =&gt; 98&#13;
    [5] =&gt; 100&#13;
)&#13;
*/&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Take note that the inner loop starts from i.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;&#13;
</description><pubDate>Mon, 14 Aug 2017 06:46:38 +0000</pubDate></item><item><title>Data Structure and Algorithm - Quick Sort</title><link>https://www.startutorial.com/articles/view/data-structure-and-algorithm-quick-sort</link><guid>https://www.startutorial.com/articles/view/data-structure-and-algorithm-quick-sort<isPermaLink>true</isPermaLink></guid><description> &lt;blockquote&gt;In this tutorial, we will learn a simple sorting algorithm - Quick Sort.&lt;/blockquote&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Problem to Solve&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Pseudocode&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;PHP Implementation&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Problem to Solve&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Given a list of numbers as shown below, please sort them in ascending order.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
                    $numbers = [21,25,100,98,89,77];&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Requirements&lt;/strong&gt;:&lt;/p&gt;&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;You are required to use Quick Sort algorithm when sorting the numbers.&lt;/li&gt;&#13;
                    &lt;li&gt;You are required to implement the algorithm in PHP language.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Pseudocode&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Quick Sort is also a divide and conquer algorithm, similar to Merge Sort.&#13;
                    It works by choosing an element(pivot) from the list and placing elements that are&#13;
                    less than the pivot on its left side and elements that are greater than the pivot on its&#13;
                    right side.&#13;
                    We repeat the steps for both left side and right side until the list can no longer be&#13;
                    divided.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Choosing a pivot can be tricky, normally we just use the first or the last element.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;img src="https://www.startutorial.com/img/quick-sort.jpg" class="thumbnail"&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Pseudocode of Quick Sort algorithm can be written as follows:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
PROCEDURE function quickSort&#13;
    IF list is empty&#13;
        Return the list&#13;
    END IF&#13;
&#13;
    Choose first element as the pivot&#13;
&#13;
    FOR each element of the list start from position 1&#13;
&#13;
        IF element is greater than pivot&#13;
            Assign it to the left side&#13;
        ELSE&#13;
            Assign it to the right side&#13;
        END IF&#13;
&#13;
    END FOR&#13;
&#13;
    return quickSort(left)+pivot+quickSort(right)&#13;
&#13;
END PROCEDURE&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. PHP Implementation&lt;/h6&gt;&#13;
                &lt;p&gt;As we can see, we are using recursion for this algorithm.&#13;
                    Typically, a divide and conquer algorithm implies the algorithm can be written&#13;
                recursively.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
$arrayToSort = [21, 25, 100, 98, 89, 77];&#13;
&#13;
function quickSort($data)&#13;
{&#13;
    if (count($data) == 0) {&#13;
        return $data;&#13;
    }&#13;
&#13;
    $pivot = $data[0];&#13;
&#13;
    $left = $right = [];&#13;
&#13;
    for ($i = 1; $i &lt; count($data); $i++) {&#13;
        if ($data[$i] &lt; $pivot) {&#13;
            $left[] = $data[$i];&#13;
        } else {&#13;
            $right[] = $data[$i];&#13;
        }&#13;
    }&#13;
&#13;
    return array_merge(quicksort($left), array($pivot), quicksort($right));&#13;
}&#13;
&#13;
print_r(quickSort($arrayToSort));&#13;
&#13;
// Output:&#13;
/*&#13;
Array&#13;
(&#13;
    [0] =&gt; 21&#13;
    [1] =&gt; 25&#13;
    [2] =&gt; 77&#13;
    [3] =&gt; 89&#13;
    [4] =&gt; 98&#13;
    [5] =&gt; 100&#13;
)&#13;
*/&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Quick Sort is indeed very simple to implement as a divide and conquer algorithm.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Mon, 14 Aug 2017 06:45:19 +0000</pubDate></item><item><title>Data Structure and Algorithm - Merge Sort</title><link>https://www.startutorial.com/articles/view/data-structure-and-algorithm-merge-sort</link><guid>https://www.startutorial.com/articles/view/data-structure-and-algorithm-merge-sort<isPermaLink>true</isPermaLink></guid><description>   &lt;blockquote&gt;In this tutorial, we will learn a simple sorting algorithm - Merge Sort.&lt;/blockquote&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Problem to Solve&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Pseudocode&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;PHP Implementation&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Problem to Solve&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Given a list of numbers as shown below, please sort them in ascending order.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
                    $numbers = [21,25,100,98,89,77];&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Requirements&lt;/strong&gt;:&lt;/p&gt;&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;You are required to use Merge Sort algorithm when sorting the numbers.&lt;/li&gt;&#13;
                    &lt;li&gt;You are required to implement the algorithm in PHP language.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Pseudocode&lt;/h6&gt;&#13;
                &lt;p&gt;Merge Sort is a divide and conquer algorithm.&#13;
                    It works by continually splitting a list in half until both halves are sorted, then the&#13;
                    operation merge is performed to combine two lists into one sorted new list.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;When splitting a list, we consider the list is sorted if it contains zero or one element.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Split&lt;/strong&gt;:&lt;/p&gt;&#13;
                &lt;p&gt;&#13;
                    &lt;img src="https://www.startutorial.com/img/merge-sort-split.jpg" class="thumbnail"&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Merge&lt;/strong&gt;:&lt;/p&gt;&#13;
                &lt;p&gt;&#13;
                    &lt;img src="https://www.startutorial.com/img/merge-sort-merge.jpg" class="thumbnail"&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Pseudocode of Merge Sort algorithm can be written as follows:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
PROCEDURE function mergeSort&#13;
   FOR each element of the master list indexed by i&#13;
&#13;
       if ( i &lt;= 1 ) return a&#13;
&#13;
       var left = a[0] to a[i/2]&#13;
       var right = a[i/2+1] to a[i]&#13;
&#13;
       left = mergeSort( left )&#13;
       right = mergeSort( right )&#13;
&#13;
       return merge( left,right )&#13;
&#13;
   END FOR&#13;
END PROCEDURE&#13;
&#13;
PROCEDURE function mergeSort&#13;
    WHILE length(left) &gt; 0 and length(right) &gt; 0&#13;
        if first(left) â‰¤ first(right)&#13;
            append first(left) to result&#13;
            left = rest(left)&#13;
        else&#13;
            append first(right) to result&#13;
            right = rest(right)&#13;
&#13;
    IF length(left) &gt; 0&#13;
        append left to result&#13;
    END IF&#13;
&#13;
    IF length(right) &gt; 0&#13;
        append right to result&#13;
    END IF&#13;
&#13;
    return result&#13;
END PROCEDURE&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. PHP Implementation&lt;/h6&gt;&#13;
                &lt;p&gt;&#13;
                    As we can see, there are two procedures in this algorithm. This leads us&#13;
                    to two PHP functions, where the first function(mergeSort) involves a recursion.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
$arrayToSort = [21, 25, 100, 98, 89, 77];&#13;
&#13;
function mergeSort($data)&#13;
{&#13;
    if (count($data) &lt;= 1) {&#13;
        return $data;&#13;
    }&#13;
&#13;
    $left = array_slice($data, 0, intval((count($data) / 2)));&#13;
    $right = array_slice($data, intval(count($data) / 2));&#13;
&#13;
    $left = mergeSort($left);&#13;
    $right = mergeSort($right);&#13;
&#13;
    return merge($left, $right);&#13;
}&#13;
&#13;
function merge($left, $right)&#13;
{&#13;
    $sorted = [];&#13;
&#13;
    while (count($left) &gt; 0 &amp;&amp; count($right) &gt; 0) {&#13;
        if ($left[0] &lt; $right[0]) {&#13;
            $firstLeft = array_shift($left);&#13;
            $sorted[] = $firstLeft;&#13;
        } else {&#13;
            $firstRight = array_shift($right);&#13;
            $sorted[] = $firstRight;&#13;
        }&#13;
    }&#13;
&#13;
    for ($i = 0; $i &lt; count($left); $i++)&#13;
        $sorted[] = $left[$i];&#13;
&#13;
    for ($i = 0; $i &lt; count($right); $i++)&#13;
        $sorted[] = $right[$i];&#13;
&#13;
    return $sorted;&#13;
}&#13;
&#13;
print_r(mergeSort($arrayToSort));&#13;
&#13;
// Output:&#13;
/*&#13;
Array&#13;
(&#13;
    [0] =&gt; 21&#13;
    [1] =&gt; 25&#13;
    [2] =&gt; 77&#13;
    [3] =&gt; 89&#13;
    [4] =&gt; 98&#13;
    [5] =&gt; 100&#13;
)&#13;
*/&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    We have followed the pseudocode strictly to implement the algorithm in PHP.&#13;
                    The only parts that we want to highlight are a couple of built-in PHP array functions:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&lt;strong&gt;array_slice&lt;/strong&gt;: It extracts a slice of the array.&#13;
                        This function is handy when we want to a certain part of the array.&lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&lt;strong&gt;array_shift&lt;/strong&gt;: It remove an element from the beginning of an array.&#13;
                        This function is handy when we want to remove the first element of the array.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;&#13;
</description><pubDate>Mon, 14 Aug 2017 06:43:08 +0000</pubDate></item><item><title>Data Structure and Algorithm - Insertion Sort</title><link>https://www.startutorial.com/articles/view/data-structure-and-algorithm-insertion-sort</link><guid>https://www.startutorial.com/articles/view/data-structure-and-algorithm-insertion-sort<isPermaLink>true</isPermaLink></guid><description>&lt;blockquote&gt;In this tutorial, we will learn a simple sorting algorithm - Insertion Sort.&lt;/blockquote&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Problem to Solve&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Pseudocode&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;PHP Implementation&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Problem to Solve&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Given a list of numbers as shown below, please sort them in ascending order.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
                    $numbers = [21,25,100,98,89,77];&#13;
&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Requirements&lt;/strong&gt;:&lt;/p&gt;&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;You are required to use Insertion Sort algorithm when sorting the numbers.&lt;/li&gt;&#13;
                    &lt;li&gt;You are required to implement the algorithm in PHP language.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Pseudocode&lt;/h6&gt;&#13;
                &lt;p&gt;Insertion Sort works by maintaining a sorted sub-list, extracting the master list's items&#13;
                    one by one and inserting them into a the sub-list until all items are&#13;
                    moved from master list to the sub-list.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;img src="https://www.startutorial.com/img/insertion-sort.jpg" class="thumbnail"&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Pseudocode of Insertion Sort algorithm can be written as follows:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
FOR each element of the master list&#13;
&#13;
    Extract the current item&#13;
&#13;
        Locate the position to insert by comparing with items from sub-list&#13;
&#13;
        Insert the item to the position&#13;
&#13;
END FOR&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. PHP Implementation&lt;/h6&gt;&#13;
                &lt;p&gt;We need a FOR loop and a WHILE loop. We are using the FOR loop to iterate the master list and&#13;
                the WHILE loop to locate the position to insert the item. &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
$masterList = [21, 25, 100, 98, 89, 77];&#13;
&#13;
$subList = [];&#13;
&#13;
for ($i = 0; $i &lt; count($masterList); $i++) {&#13;
&#13;
    $extractItem = $masterList[$i];&#13;
&#13;
    $subList[] = $extractItem;&#13;
&#13;
    // Locate the position to insert by comparing with items from sub-list&#13;
    $positionFound = $i;&#13;
&#13;
    while ($positionFound &gt; 0 &amp;&amp; $extractItem &lt; $subList[$positionFound - 1]) {&#13;
        $subList[$positionFound] = $subList[$positionFound - 1];&#13;
        $positionFound = $positionFound - 1;&#13;
    }&#13;
&#13;
    // Insert the item to the position&#13;
    $subList[$positionFound] = $extractItem;&#13;
&#13;
}&#13;
&#13;
print_r($subList);&#13;
&#13;
// Output:&#13;
/*&#13;
Array&#13;
(&#13;
    [0] =&gt; 21&#13;
    [1] =&gt; 25&#13;
    [2] =&gt; 77&#13;
    [3] =&gt; 89&#13;
    [4] =&gt; 98&#13;
    [5] =&gt; 100&#13;
)&#13;
*/&#13;
&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;The only piece that needs a bit of explanation is the probably the WHILE loop.&#13;
                Pay attention to the conditions of the loop, besides the constraint of the sub-list's length, we also need&#13;
                    to make sure that we do not run the loop when we extract the first element ($positionFound=0).&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;&#13;
</description><pubDate>Mon, 14 Aug 2017 06:40:28 +0000</pubDate></item><item><title>Data Structure and Algorithm - Bubble Sort</title><link>https://www.startutorial.com/articles/view/data-structure-and-algorithm-bubble-sort</link><guid>https://www.startutorial.com/articles/view/data-structure-and-algorithm-bubble-sort<isPermaLink>true</isPermaLink></guid><description>   &lt;blockquote&gt;In this tutorial, we will learn a simple sorting algorithm - Bubble Sort.&lt;/blockquote&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Problem to Solve&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Pseudocode&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;PHP Implementation&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Problem to Solve&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Given a list of numbers as shown below, please sort them in ascending order.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
                    $numbers = [21,25,100,98,89,77];&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Requirements&lt;/strong&gt;:&lt;/p&gt;&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;You are required to use Bubble Sort algorithm when sorting the numbers.&lt;/li&gt;&#13;
                    &lt;li&gt;You are required to implement the algorithm in PHP language.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Pseudocode&lt;/h6&gt;&#13;
                &lt;p&gt;Bubble Sort works by comparing two values at a time and does it pair by pair.&#13;
                   And it iterates until all elements are in place.&#13;
                   After each iteration, at least one element is moved to the end of the list.&#13;
                   Below is an illustration of the first iteration.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;img src="https://www.startutorial.com/img/bubble-sort-i-1.jpg" class="thumbnail"&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Pseudocode of Bubble Sort algorithm can be written as follows:&lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
FOR each element of the list&#13;
&#13;
    FOR each element of the list&#13;
&#13;
        IF current element greater then next element&#13;
&#13;
            swap the elements&#13;
&#13;
        END IF&#13;
&#13;
    END FOR&#13;
&#13;
END FOR&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;The inner loop is considered one iteration and the outer loop makes sure we iterate enough times to&#13;
                sort the list.&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. PHP Implementation&lt;/h6&gt;&#13;
                &lt;p&gt;To implement Bubble Sort in PHP, all we need is two loops. Note that the termination of both loops is:&#13;
                   the length of the list - 1. This is to prevent from accessing un-indexed element.&lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
$numbers = [21, 25, 100, 98, 89, 77];&#13;
&#13;
for ($i = 0; $i &lt; (count($numbers) - 1); $i++) {&#13;
&#13;
    for ($j = 0; $j &lt; (count($numbers) - 1); $j++) {&#13;
&#13;
        if ($numbers[$j] &gt; $numbers[$j + 1]) {&#13;
&#13;
            $tmp = $numbers[$j];&#13;
&#13;
            $numbers[$j] = $numbers[$j + 1];&#13;
&#13;
            $numbers[$j + 1] = $tmp;&#13;
        }&#13;
    }&#13;
}&#13;
&#13;
print_r($numbers);&#13;
&#13;
// Output:&#13;
/*&#13;
Array&#13;
(&#13;
    [0] =&gt; 21&#13;
    [1] =&gt; 25&#13;
    [2] =&gt; 77&#13;
    [3] =&gt; 89&#13;
    [4] =&gt; 98&#13;
    [5] =&gt; 100&#13;
)&#13;
*/&#13;
&lt;/script&gt;&#13;
&#13;
&#13;
&#13;
&#13;
&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;&#13;
&#13;
</description><pubDate>Mon, 14 Aug 2017 06:36:13 +0000</pubDate></item><item><title>Your first GraphQL API - Search</title><link>https://www.startutorial.com/articles/view/your-first-graphql-api-search</link><guid>https://www.startutorial.com/articles/view/your-first-graphql-api-search<isPermaLink>true</isPermaLink></guid><description>&lt;blockquote&gt;Search is another complementary technical when working with a large dataset.&#13;
                    It takes an existing list, and removes items based on criteria that match/don't match.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;In this tutorial, we are going to implement a search for our data table.&lt;/p&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Understanding GraphQL searching mechanism&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Implementing searching&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Understanding GraphQL searching mechanism&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Search happens when we pass in a search parameter and it scans multiple fields behind the scene&#13;
                    to get the data we want. We can use the same idea to implement filters, except that filters&#13;
                work in one single field.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Search can go together with pagination or alone. In our case, we are going to combine search and&#13;
                    pagination.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Implementing searching&lt;/h6&gt;&#13;
                &lt;p&gt;An imaginary searching request would look like this: &lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
{&#13;
   articlesConnection&#13;
   (&#13;
        search: "First"&#13;
   )&#13;
   {&#13;
      edges {&#13;
        node {&#13;
          title&#13;
        }&#13;
        cursor&#13;
      }&#13;
   }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
                &lt;p&gt;Note that we are using a generic "search" parameter for the query argument:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
search: "First"&#13;
                &lt;/script&gt;&#13;
                &lt;p&gt;Since in a search request, we are trying to narrow down the result, there is no need to&#13;
                paginate the result.&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&#13;
                    Let's add "search" parameter to the &lt;strong&gt;ArticlesConnection&lt;/strong&gt; field.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Modify &lt;strong&gt;build&lt;/strong&gt; method of &lt;strong&gt;ArticlesConnection&lt;/strong&gt; class:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
public function build(FieldConfig $config)&#13;
{&#13;
    $this-&gt;addArguments(array_merge(&#13;
        Connection::connectionArgs(),&#13;
        ['sort' =&gt; new SortingParamsType(new ArticleType(), ['id'])],&#13;
        ['search' =&gt; new StringType()]&#13;
    ));&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Next step is to make &lt;strong&gt;resolve&lt;/strong&gt; method capable of searching the results based on&#13;
                    our request. Normally this method will delegate to the other service class from&#13;
                    business layer, and the service class will search the results with some sort of database calls.&#13;
                    However, because our fake repository class simply returns a static array, we are going to sort&#13;
                    with PHP array method &lt;strong&gt;array_filter&lt;/strong&gt;.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Modify &lt;strong&gt;resolve&lt;/strong&gt; method of &lt;strong&gt;ArticlesConnection&lt;/strong&gt; class:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
public function resolve($value, array $args, ResolveInfo $info)&#13;
{&#13;
    $result = ArticlesRepository::findAll();&#13;
&#13;
    $result = $this-&gt;sortedResult($result, $args);&#13;
&#13;
    $result = $this-&gt;searchResult($result, $args);&#13;
&#13;
    return ArrayConnection::connectionFromArray($result, $args);&#13;
}&#13;
&#13;
private function searchResult($result, array $args)&#13;
{&#13;
    if (!isset($args['search'])) {&#13;
        return $result;&#13;
    }&#13;
&#13;
    return array_filter($result, function ($item) use ($args) {&#13;
        return strpos($item['title'], $args['search']) !== false;&#13;
    });&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;That is all the change we need for &lt;strong&gt;ArcilesConnection&lt;/strong&gt; class and the final file should&#13;
                    be as shown below:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
namespace StarTutorial\Field;&#13;
&#13;
&#13;
use StarTutorial\Repository\ArticlesRepository;&#13;
use StarTutorial\Type\ArticleType;&#13;
use Youshido\GraphQL\Config\Field\FieldConfig;&#13;
use Youshido\GraphQL\Execution\ResolveInfo;&#13;
use Youshido\GraphQL\Field\AbstractField;&#13;
use Youshido\GraphQL\Relay\Connection\ArrayConnection;&#13;
use Youshido\GraphQL\Relay\Connection\Connection;&#13;
use Youshido\GraphQL\Type\Scalar\StringType;&#13;
use Youshido\GraphQLExtension\Type\CursorResultType;&#13;
use Youshido\GraphQLExtension\Type\Sorting\SortingParamsType;&#13;
&#13;
class ArticlesConnection extends AbstractField&#13;
{&#13;
&#13;
    public function getType()&#13;
    {&#13;
        return new CursorResultType(new ArticleType());&#13;
    }&#13;
&#13;
    public function build(FieldConfig $config)&#13;
    {&#13;
        $this-&gt;addArguments(array_merge(&#13;
            Connection::connectionArgs(),&#13;
            ['sort' =&gt; new SortingParamsType(new ArticleType(), ['id'])],&#13;
            ['search' =&gt; new StringType()]&#13;
        ));&#13;
    }&#13;
&#13;
    public function resolve($value, array $args, ResolveInfo $info)&#13;
    {&#13;
        $result = ArticlesRepository::findAll();&#13;
&#13;
        $result = $this-&gt;sortedResult($result, $args);&#13;
&#13;
        $result = $this-&gt;searchResult($result, $args);&#13;
&#13;
        return ArrayConnection::connectionFromArray($result, $args);&#13;
    }&#13;
&#13;
    private function sortedResult($result, array $args)&#13;
    {&#13;
        if (!isset($args['sort'])) {&#13;
            return $result;&#13;
        }&#13;
&#13;
        $field = $args['sort']['field'];&#13;
&#13;
        $order = $args['sort']['order'];&#13;
&#13;
        uasort($result, function ($a, $b) use ($field, $order) {&#13;
            if (1 == $order) {&#13;
                return $a[$field] - $b[$field];&#13;
            }&#13;
            if (-1 == $order) {&#13;
                return $b[$field] - $a[$field];&#13;
            }&#13;
        });&#13;
&#13;
        return $result;&#13;
    }&#13;
&#13;
    private function searchResult($result, array $args)&#13;
    {&#13;
        if (!isset($args['search'])) {&#13;
            return $result;&#13;
        }&#13;
&#13;
        return array_filter($result, function ($item) use ($args) {&#13;
            return strpos($item['title'], $args['search']) !== false;&#13;
        });&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;Lastly, we need to create a simple request to search the result using "search" parameter:&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Create a new file &lt;strong&gt;tutorial-search.php&lt;/strong&gt;:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&amp;lt;?php&#13;
&#13;
use StarTutorial\Field\ArticleField;&#13;
use StarTutorial\Field\ArticlesConnection;&#13;
use Youshido\GraphQL\Execution\Processor;&#13;
use Youshido\GraphQL\Schema\Schema;&#13;
use Youshido\GraphQL\Type\Object\ObjectType;&#13;
&#13;
require_once 'vendor/autoload.php';&#13;
&#13;
$processor = new Processor(new Schema([&#13;
    'query' =&gt; new ObjectType([&#13;
        'name' =&gt; 'RootQueryType',&#13;
        'fields' =&gt; [&#13;
            new ArticleField(),&#13;
            new ArticlesConnection()&#13;
        ]&#13;
    ]),&#13;
]));&#13;
&#13;
$processor-&gt;processPayload(&#13;
    '{ articlesConnection(search: "First"){edges { node { id, title } cursor }} }'&#13;
);&#13;
&#13;
echo '&lt;pre&gt;';&#13;
echo json_encode($processor-&gt;getResponseData()) . "\n";&#13;
echo '&lt;pre&gt;';&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Access the page from the browser of your choice via the URL&#13;
                    http://your-local-php-server/tutorial-search.php. &lt;/p&gt;&#13;
                &lt;p&gt;You should expect a JSON output as shown below if you have followed this tutorial correctly: &lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: text"&gt;&#13;
{&#13;
   "data":{&#13;
      "articlesConnection":{&#13;
         "edges":[&#13;
            {&#13;
               "node":{&#13;
                  "id":1,&#13;
                  "title":"My First GraphQL API"&#13;
               },&#13;
               "cursor":"YXJyYXljb25uZWN0aW9uOjA="&#13;
            }&#13;
         ]&#13;
      }&#13;
   }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Try to change the "search" parameter's value and see how GraphQL searching reflects.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Next tutorial, we are going to show you how to implement nested queries in GraphQL and see&#13;
                    how GraphQL loads data dynamically on the fly.&#13;
                    &lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Mon, 15 May 2017 22:06:01 +0000</pubDate></item><item><title>Your first GraphQL API - Sorting</title><link>https://www.startutorial.com/articles/view/your-first-graphql-api-sorting</link><guid>https://www.startutorial.com/articles/view/your-first-graphql-api-sorting<isPermaLink>true</isPermaLink></guid><description> &lt;blockquote&gt;Similar to pagination, sorting is another complementary technical for loading large data&#13;
                    set.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;In this tutorial, we are going to implement sorting for our articles table.&lt;/p&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Understanding GraphQL sorting mechanism&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Implementing sorting&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Understanding GraphQL sorting mechanism&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;The mechanism behind sorting is much simpler comparing to pagination.&#13;
                    We pass in a field and its order to the request and we get the results accordingly.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;In most cases, sorting goes together with pagination and we are going to do the same&#13;
                for our example.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Implementing sorting&lt;/h6&gt;&#13;
                &lt;p&gt;An imaginary sorting and pagination request would look like this: &lt;/p&gt;&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
{&#13;
   articlesConnection&#13;
   (&#13;
        first:2,&#13;
        sort:{&#13;
          field:id,&#13;
          order:ASC&#13;
        }&#13;
   )&#13;
   {&#13;
      edges {&#13;
        node {&#13;
          title&#13;
        }&#13;
        cursor&#13;
      }&#13;
      pageInfo {&#13;
        endCursor&#13;
        hasNextPage&#13;
      }&#13;
   }&#13;
}&#13;
                &lt;/script&gt;&#13;
                &lt;p&gt;The only additional code block is the sort parameter:&lt;/p&gt;&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
sort:{&#13;
    field:id,&#13;
    order:ASC&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;a href="https://github.com/Youshido/GraphQLExtensions" target="_blank"&gt;GraphQL Extensions&lt;/a&gt; provides&#13;
                reusable classes for sorting similar to pagination.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;First step is to add available sort parameters to the &lt;strong&gt;ArticlesConnection&lt;/strong&gt; field. To keep&#13;
                    our tutorial simple, we will make "id" field available as the only sort parameter.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Modify &lt;strong&gt;build&lt;/strong&gt; method of &lt;strong&gt;ArticlesConnection&lt;/strong&gt; class:&lt;/p&gt;&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
public function build(FieldConfig $config)&#13;
{&#13;
    $this-&gt;addArguments(array_merge(&#13;
        Connection::connectionArgs(),&#13;
        ['sort' =&gt; new SortingParamsType(new ArticleType(), ['id'])]&#13;
    ));&#13;
}&#13;
&lt;/script&gt;&#13;
            &lt;p&gt;We are using the &lt;strong&gt;SortingParamsType&lt;/strong&gt; class from &lt;strong&gt;GraphQL Extensions&lt;/strong&gt; to&#13;
            build the sorting parameter.&lt;/p&gt;&#13;
&#13;
            &lt;p&gt;Next step is to make &lt;strong&gt;resolve&lt;/strong&gt; method capable of sorting the results based on&#13;
            our request. Normally this method will delegate to the other service class from&#13;
                business layer, and the service class will sort the results with some sort of database calls.&#13;
                However, because our fake repository class simply returns a static array, we are going to sort&#13;
            with PHP array method &lt;strong&gt;uasort&lt;/strong&gt;.&lt;/p&gt;&#13;
&#13;
            &lt;p&gt;Modify &lt;strong&gt;resolve&lt;/strong&gt; method of &lt;strong&gt;ArticlesConnection&lt;/strong&gt; class:&lt;/p&gt;&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
public function resolve($value, array $args, ResolveInfo $info)&#13;
{&#13;
    $result = ArticlesRepository::findAll();&#13;
&#13;
    $result = $this-&gt;sortedResult($result, $args);&#13;
&#13;
    return ArrayConnection::connectionFromArray($result, $args);&#13;
}&#13;
&#13;
private function sortedResult($result, array $args)&#13;
{&#13;
    if (!isset($args['sort'])) {&#13;
        return $result;&#13;
    }&#13;
&#13;
    $field = $args['sort']['field'];&#13;
&#13;
    $order = $args['sort']['order'];&#13;
&#13;
    uasort($result, function ($a, $b) use ($field, $order) {&#13;
        if (1 == $order) {&#13;
            return $a[$field] - $b[$field];&#13;
        }&#13;
        if (-1 == $order) {&#13;
            return $b[$field] - $a[$field];&#13;
        }&#13;
    });&#13;
&#13;
    return $result;&#13;
}&#13;
&lt;/script&gt;&#13;
        &lt;p&gt;Note the value of "DESC" is -1 and "ASC" is 1 from &lt;strong&gt;$args&lt;/strong&gt;.&lt;/p&gt;&#13;
&#13;
        &lt;p&gt;That is all the change we need for &lt;strong&gt;ArcilesConnection&lt;/strong&gt; class and the final file should be as shown below:&lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
namespace StarTutorial\Field;&#13;
&#13;
&#13;
use StarTutorial\Repository\ArticlesRepository;&#13;
use StarTutorial\Type\ArticleType;&#13;
use Youshido\GraphQL\Config\Field\FieldConfig;&#13;
use Youshido\GraphQL\Execution\ResolveInfo;&#13;
use Youshido\GraphQL\Field\AbstractField;&#13;
use Youshido\GraphQL\Relay\Connection\ArrayConnection;&#13;
use Youshido\GraphQL\Relay\Connection\Connection;&#13;
use Youshido\GraphQLExtension\Type\CursorResultType;&#13;
use Youshido\GraphQLExtension\Type\Sorting\SortingParamsType;&#13;
&#13;
class ArticlesConnection extends AbstractField&#13;
{&#13;
&#13;
    public function getType()&#13;
    {&#13;
        return new CursorResultType(new ArticleType());&#13;
    }&#13;
&#13;
    public function build(FieldConfig $config)&#13;
    {&#13;
        $this-&gt;addArguments(array_merge(&#13;
            Connection::connectionArgs(),&#13;
            ['sort' =&gt; new SortingParamsType(new ArticleType(), ['id'])]&#13;
        ));&#13;
    }&#13;
&#13;
    public function resolve($value, array $args, ResolveInfo $info)&#13;
    {&#13;
        $result = ArticlesRepository::findAll();&#13;
&#13;
        $result = $this-&gt;sortedResult($result, $args);&#13;
&#13;
        return ArrayConnection::connectionFromArray($result, $args);&#13;
    }&#13;
&#13;
    private function sortedResult($result, array $args)&#13;
    {&#13;
        if (!isset($args['sort'])) {&#13;
            return $result;&#13;
        }&#13;
&#13;
        $field = $args['sort']['field'];&#13;
&#13;
        $order = $args['sort']['order'];&#13;
&#13;
        uasort($result, function ($a, $b) use ($field, $order) {&#13;
            if (1 == $order) {&#13;
                return $a[$field] - $b[$field];&#13;
            }&#13;
            if (-1 == $order) {&#13;
                return $b[$field] - $a[$field];&#13;
            }&#13;
        });&#13;
&#13;
        return $result;&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;Lastly, we need to create a simple request to sort the result using id field:&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Create a new file &lt;strong&gt;tutorial-sorting.php&lt;/strong&gt;:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&amp;lt;?php&#13;
&#13;
use StarTutorial\Field\ArticleField;&#13;
use StarTutorial\Field\ArticlesConnection;&#13;
use Youshido\GraphQL\Execution\Processor;&#13;
use Youshido\GraphQL\Schema\Schema;&#13;
use Youshido\GraphQL\Type\Object\ObjectType;&#13;
&#13;
require_once 'vendor/autoload.php';&#13;
&#13;
$processor = new Processor(new Schema([&#13;
    'query' =&gt; new ObjectType([&#13;
        'name' =&gt; 'RootQueryType',&#13;
        'fields' =&gt; [&#13;
            new ArticleField(),&#13;
            new ArticlesConnection()&#13;
        ]&#13;
    ]),&#13;
]));&#13;
&#13;
$processor-&gt;processPayload(&#13;
    '{ articlesConnection(first:2, sort: {field: id, order: ASC}){edges { node { id, title } cursor }, pageInfo { endCursor hasNextPage }} }'&#13;
);&#13;
&#13;
echo '&lt;pre&gt;';&#13;
echo json_encode($processor-&gt;getResponseData()) . "\n";&#13;
echo '&lt;pre&gt;';&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Access the page from the browser of your choice via the URL&#13;
                    http://your-local-php-server/tutorial-sorting.php. &lt;/p&gt;&#13;
                &lt;p&gt;You should expect a JSON output as shown below if you have followed this tutorial correctly: &lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: text"&gt;&#13;
{&#13;
   "data":{&#13;
      "articlesConnection":{&#13;
         "edges":[&#13;
            {&#13;
               "node":{&#13;
                  "id":1,&#13;
                  "title":"My First GraphQL API"&#13;
               },&#13;
               "cursor":"YXJyYXljb25uZWN0aW9uOjA="&#13;
            },&#13;
            {&#13;
               "node":{&#13;
                  "id":2,&#13;
                  "title":"GraphQL History"&#13;
               },&#13;
               "cursor":"YXJyYXljb25uZWN0aW9uOjE="&#13;
            }&#13;
         ],&#13;
         "pageInfo":{&#13;
            "endCursor":"YXJyYXljb25uZWN0aW9uOjE=",&#13;
            "hasNextPage":true&#13;
         }&#13;
      }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Try to change the order parameter's value(DESC or ASC) and see how GraphQL sorting reflects.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Next tutorial, we will implement search feature.&#13;
                    &lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Sat, 13 May 2017 22:50:40 +0000</pubDate></item><item><title>Your first GraphQL API - Pagination</title><link>https://www.startutorial.com/articles/view/your-first-graphql-api-pagination</link><guid>https://www.startutorial.com/articles/view/your-first-graphql-api-pagination<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;Pagination is a common technique for loading large data set. It provides good&#13;
                    user experience without sacrificing server performance. &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;In this tutorial, we are going to implement pagination for our data table.&lt;/p&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Creating more data for pagination&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Understanding GraphQL pagination mechanism&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Implementing pagination&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Creating more data for pagination&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    It may cause a performance issue if you have a huge amount of records in your database and&#13;
                    you try to load them at once.&#13;
                    The idea of pagination is to ease server from loading huge amount of data at once, by allowing&#13;
                    users to navigate all your records page by page.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;We need to create more records to demonstrate pagination properly in this tutorial.&#13;
                Open ArticlesRepository file and let's add some more records:  &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;src/Repository/ArticlesRepository&lt;/strong&gt;:&lt;/p&gt;&#13;
&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&amp;lt;?php&#13;
namespace StarTutorial\Repository;&#13;
&#13;
class ArticlesRepository&#13;
{&#13;
&#13;
    public static function findAll()&#13;
    {&#13;
        return [&#13;
            [&#13;
                'id' =&gt; 1,&#13;
                'title' =&gt; 'My First GraphQL API',&#13;
                'content' =&gt; 'It is all about GraphQL',&#13;
                'created' =&gt; new \DateTime('2017-02-24 11:20:10'),&#13;
                'author_id' =&gt; 1,&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 2,&#13;
                'title' =&gt; 'GraphQL History',&#13;
                'content' =&gt; 'GraphQL is created by Facebook',&#13;
                'created' =&gt; new \DateTime('2017-03-27 12:20:10'),&#13;
                'author_id' =&gt; 2&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 3,&#13;
                'title' =&gt; 'GraphQL vs Rest',&#13;
                'content' =&gt; 'GraphQL is a query language, whereas Rest is a protocol',&#13;
                'created' =&gt; new \DateTime('2017-04-30 13:20:10'),&#13;
                'author_id' =&gt; 2&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 4,&#13;
                'title' =&gt; 'GraphQL vs Rest Round 1',&#13;
                'content' =&gt; 'GraphQL is wins 1st battle',&#13;
                'created' =&gt; new \DateTime('2017-05-01 13:20:10'),&#13;
                'author_id' =&gt; 2&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 5,&#13;
                'title' =&gt; 'GraphQL vs Rest Round 2',&#13;
                'content' =&gt; 'GraphQL is wins 2nd battle',&#13;
                'created' =&gt; new \DateTime('2017-05-02 13:20:10'),&#13;
                'author_id' =&gt; 2&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 6,&#13;
                'title' =&gt; 'GraphQL vs Rest Round 3',&#13;
                'content' =&gt; 'GraphQL is wins 3rd battle',&#13;
                'created' =&gt; new \DateTime('2017-05-03 13:20:10'),&#13;
                'author_id' =&gt; 2&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 7,&#13;
                'title' =&gt; 'GraphQL vs Rest Round 4',&#13;
                'content' =&gt; 'GraphQL is wins 4th battle',&#13;
                'created' =&gt; new \DateTime('2017-05-04 13:20:10'),&#13;
                'author_id' =&gt; 2&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 8,&#13;
                'title' =&gt; 'GraphQL vs Rest Round 5',&#13;
                'content' =&gt; 'GraphQL is wins 5th battle',&#13;
                'created' =&gt; new \DateTime('2017-05-05 13:20:10'),&#13;
                'author_id' =&gt; 2&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 9,&#13;
                'title' =&gt; 'GraphQL vs Rest Round 6',&#13;
                'content' =&gt; 'GraphQL is wins 6th battle',&#13;
                'created' =&gt; new \DateTime('2017-05-06 13:20:10'),&#13;
                'author_id' =&gt; 2&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 10,&#13;
                'title' =&gt; 'GraphQL vs Rest Round 7',&#13;
                'content' =&gt; 'GraphQL is wins 7th battle',&#13;
                'created' =&gt; new \DateTime('2017-05-07 13:20:10'),&#13;
                'author_id' =&gt; 2&#13;
            ]&#13;
        ];&#13;
    }&#13;
}&lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Understanding GraphQL pagination mechanism&lt;/h6&gt;&#13;
                &lt;p&gt;There are a number of different ways of implementing pagination in general.&#13;
                Whereas in GraphQL, the best practice is using cursor based pagination.&lt;/p&gt;&#13;
                &lt;p&gt;There is a full page explaining what cursor based pagination is in&#13;
                    &lt;a href="http://graphql.org/learn/pagination/" target="_blank"&gt;GraphQL official page&lt;/a&gt;.&#13;
                    We encourage that you take look at it and understand the basis of it. However do not worry about&#13;
                    too much if you are not able to get the full understanding of it at first try, we will go through&#13;
                    the process of implementation later on.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;In short, cursor based pagination returns cursors along with data records as well as&#13;
                some page related information such as whether it has reached the end, has previous page, has next page and so on.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. Implementing pagination&lt;/h6&gt;&#13;
                &lt;p&gt;An imaginary pagination request would look like this: &lt;/p&gt;&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
{&#13;
  articlesConnection(first:2 after:"Y3Vyc29yMQ==") {&#13;
      edges {&#13;
        node {&#13;
          title&#13;
        }&#13;
        cursor&#13;
      }&#13;
      pageInfo {&#13;
        endCursor&#13;
        hasNextPage&#13;
      }&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;As you might have noticed. Some parts of the request have some arbitrary names such as&#13;
                edges, node, cursor as well as pageInfo. They seem reusable and we can make some generic class&#13;
                for them. &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;It turns out that those pagination related classes are indeed created by someone else and make&#13;
                them into a generic package.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;The package is called &lt;a href="https://github.com/Youshido/GraphQLExtensions" target="_blank"&gt;GraphQL Extensions&lt;/a&gt;&#13;
                    and it provides a lot of useful utility classes for &lt;strong&gt;youshido/GraphQL&lt;/strong&gt;.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Install GraphQL Extensions:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;composer require youshido/graphql-extensions&lt;/script&gt;&#13;
&#13;
&#13;
&#13;
                &lt;p&gt;The algorithm for implementing GraphQL pagination is explained at&#13;
                    &lt;a href="https://facebook.github.io/relay/graphql/connections.htm#sec-Pagination-algorithm" target="_blank"&gt;https://facebook.github.io/relay/graphql/connections.htm#sec-Pagination-algorithm&lt;/a&gt;.&#13;
                Basically two directions we can go when traversing with a cursor and they are forward and backwards.&#13;
                And the algorithm is around how we deal with the directions. Read the article and get a rough idea how&#13;
                    the algorithm works, it is actually quite straightforward.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;With a rough idea of the algorithm in mind, create a field class &lt;strong&gt;ArticlesConnections&lt;/strong&gt; that will resolve the pagination request:&lt;/p&gt;&#13;
&#13;
    &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
    &amp;lt;?php&#13;
&#13;
&#13;
    namespace StarTutorial\Field;&#13;
&#13;
&#13;
    use StarTutorial\Repository\ArticlesRepository;&#13;
    use StarTutorial\Type\ArticleType;&#13;
    use Youshido\GraphQL\Config\Field\FieldConfig;&#13;
    use Youshido\GraphQL\Execution\ResolveInfo;&#13;
    use Youshido\GraphQL\Field\AbstractField;&#13;
    use Youshido\GraphQL\Relay\Connection\ArrayConnection;&#13;
    use Youshido\GraphQL\Relay\Connection\Connection;&#13;
    use Youshido\GraphQLExtension\Type\CursorResultType;&#13;
&#13;
    class ArticlesConnection extends AbstractField&#13;
    {&#13;
&#13;
        public function getType()&#13;
        {&#13;
            return new CursorResultType(new ArticleType());&#13;
        }&#13;
&#13;
        public function build(FieldConfig $config)&#13;
        {&#13;
            $this-&gt;addArguments(Connection::connectionArgs());&#13;
        }&#13;
&#13;
        public function resolve($value, array $args, ResolveInfo $info)&#13;
        {&#13;
            return ArrayConnection::connectionFromArray(ArticlesRepository::findAll(), $args);&#13;
        }&#13;
    }&#13;
    &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;We will run through each method from &lt;strong&gt;ArticlesConnection&lt;/strong&gt; class:&lt;/p&gt;&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&lt;strong&gt;getType()&lt;/strong&gt;: It addresses the return type of the field, which is a cursor based&#13;
                    pagination result. &lt;strong&gt;CursorResultType&lt;/strong&gt; is the reusable class that does the actual work.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&lt;strong&gt;build()&lt;/strong&gt;: Here yet we used another utility class that helps us set available arguments&#13;
                        for pagination.&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&lt;strong&gt;resolve()&lt;/strong&gt;: You should know by now, this is the resolver method that returns&#13;
                    results based on the request. Normally, this method will delegate to the other service class from&#13;
                    business layer, and the service class will trigger database calls based on the algorithm mentioned above.&#13;
                    However, because our fake repository class simply returns a static array, we can use another utility&#13;
                    class &lt;strong&gt;ArrayConnection&lt;/strong&gt; from &lt;strong&gt;youshido/GraphQL&lt;/strong&gt;. The method looks at an&#13;
                    array and filter results with request's arguments. It uses the base64 value of array index as the cursor&#13;
                    value.&#13;
                    &lt;/li&gt;&#13;
&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;The last thing we need to do is to add &lt;strong&gt;ArticlesConnection&lt;/strong&gt; to the schema.&#13;
                    Meanwhile, we will create a simple request to our schema:&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Create a new file &lt;strong&gt;tutorial-pagination.php&lt;/strong&gt;:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&amp;lt;?php&#13;
&#13;
use StarTutorial\Field\ArticleField;&#13;
use StarTutorial\Field\ArticlesConnection;&#13;
use Youshido\GraphQL\Execution\Processor;&#13;
use Youshido\GraphQL\Schema\Schema;&#13;
use Youshido\GraphQL\Type\Object\ObjectType;&#13;
&#13;
require_once 'vendor/autoload.php';&#13;
&#13;
$processor = new Processor(new Schema([&#13;
    'query' =&gt; new ObjectType([&#13;
        'name' =&gt; 'RootQueryType',&#13;
        'fields' =&gt; [&#13;
            new ArticleField(),&#13;
            new ArticlesConnection()&#13;
        ]&#13;
    ]),&#13;
]));&#13;
&#13;
$processor-&gt;processPayload(&#13;
    '{ articlesConnection(first:2, after: "YXJyYXljb25uZWN0aW9uOjE="){edges { node { title } cursor }, pageInfo { endCursor hasNextPage }} }'&#13;
);&#13;
&#13;
echo '&lt;pre&gt;';&#13;
echo json_encode($processor-&gt;getResponseData()) . "\n";&#13;
echo '&lt;pre&gt;';&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Access the page from the browser of your choice via the URL http://your-local-php-server/tutorial-pagination.php. &lt;/p&gt;&#13;
                &lt;p&gt;You should expect a JSON output as shown below if you have followed this tutorial correctly: &lt;/p&gt;&#13;
&lt;script type="syntaxhighlighter" class="brush: text"&gt;&#13;
{&#13;
	"data": {&#13;
		"articlesConnection": {&#13;
			"edges": [&#13;
				{&#13;
					"node": {&#13;
						"title": "GraphQL vs Rest"&#13;
				},&#13;
					"cursor": "YXJyYXljb25uZWN0aW9uOjI="&#13;
				},&#13;
				{&#13;
					"node": {&#13;
						"title": "GraphQL vs Rest Round 1"&#13;
				},&#13;
					"cursor": "YXJyYXljb25uZWN0aW9uOjM="&#13;
				}&#13;
			],&#13;
		"pageInfo": {&#13;
				"endCursor": "YXJyYXljb25uZWN0aW9uOjM=",&#13;
				"hasNextPage": true&#13;
			}&#13;
		}&#13;
	}&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Try to change different arguments (first, after, last and before)&#13;
                    and see how GraphQL cursor based pagination reflects.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Next tutorial, we will implement sort feature.&#13;
                    &lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Wed, 03 May 2017 06:20:01 +0000</pubDate></item><item><title>Your first GraphQL API - Introduction</title><link>https://www.startutorial.com/articles/view/your-first-graphql-api-introduction</link><guid>https://www.startutorial.com/articles/view/your-first-graphql-api-introduction<isPermaLink>true</isPermaLink></guid><description> &lt;blockquote&gt;&#13;
                    GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing&#13;
                    data. GraphQL provides a complete and understandable description of the data in your API, gives&#13;
                    clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs&#13;
                    over time, and enables powerful developer tools.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;In a nutshell, GraphQL provides a few significant benefits to making the life of API development&#13;
                    easier:&lt;/p&gt;&#13;
&#13;
                &lt;ol&gt;&#13;
                    &lt;li&gt;Ask for what you need, get exactly that.&lt;/li&gt;&#13;
                    &lt;li&gt;Get many resources in a single request.&lt;/li&gt;&#13;
                    &lt;li&gt;Describe whatâ€™s possible with a type system.&lt;/li&gt;&#13;
                    &lt;li&gt;Move faster with powerful developer tools.&lt;/li&gt;&#13;
                    &lt;li&gt;Evolve your API without versions.&lt;/li&gt;&#13;
                    &lt;li&gt;Bring your own data and code.&lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;p&gt;Head to &lt;a href="http://graphql.org/"&gt;official site&lt;/a&gt; if you want to read about more the&#13;
                    benefits GraphQL brings for us. In this series of tutorials, we will start from the basics of&#13;
                    building GraphQL API then slowly evolve to&#13;
                    more advanced topics. &lt;/p&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Setting the Goal&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Installing the Youshido/GraphQL package&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Reading an Article with ID&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Setting the Goal&lt;/h6&gt;&#13;
                &lt;p&gt;The library that we are going to use in these tutorials is &lt;strong&gt;Youshido/GraphQL&lt;/strong&gt;.&#13;
                    It is a package that will help us implement GraphQL without re-inventing the wheel.&#13;
                    &lt;strong&gt;Youshido/GraphQL&lt;/strong&gt; is a very well written and maintained project. Its excellent&#13;
                    Object-Oriented design makes it super easy to implement GraphQL in OOP fashion and that is the main&#13;
                    reason we have chosen to work with &lt;strong&gt;Youshido/GraphQL&lt;/strong&gt; over other PHP GraphQL&#13;
                    implementation.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;We will be using the OOP fashion of &lt;strong&gt;Youshido/GraphQL&lt;/strong&gt; across all tutorials. We&#13;
                    believe&#13;
                    OOP makes the code easy to maintain and simple to explain the concepts.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;We are going to build a GraphQL API for a simple blog. This blog has a series of articles and each&#13;
                    article belongs to an author. Features of our API provides include read, write, pagination, search&#13;
                    and so on. To make these tutorials focused, we will skip stuff like user authentication,&#13;
                    sophisticated business logic and other framework related stuff. &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;To keep things clear and focused, we are not going to use Database. However in reality, mostly you&#13;
                    store articles and authors records in some sort of Database. &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Just keep in mind, the whole purpose of these tutorials is to demonstrate&#13;
                    how we can use the package &lt;strong&gt;Youshido/GraphQL&lt;/strong&gt; to implement GraphQL for our own&#13;
                    application. &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Installing the Youshido/GraphQL package&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Create a folder &lt;strong&gt;blog&lt;/strong&gt; to hold our code sample.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Then we will install the Youshido/GraphQL package using Composer. Navigate to &lt;strong&gt;blog&lt;/strong&gt;&#13;
                    folder and run command as show below:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;composer require youshido/graphql&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Create three more sub-directories under &lt;strong&gt;src&lt;/strong&gt; folder:&lt;/p&gt;&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;&lt;strong&gt;src/Repository&lt;/strong&gt;: This directory stores some fake repositories that will give us&#13;
                        some&#13;
                        static articles and&#13;
                        authors' records. As mentioned earlier, we are not going to use Database in these tutorials.&#13;
                        These fake repository classes pretend to be your real repository classes.&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&lt;strong&gt;src/Field&lt;/strong&gt;: This directory stores Youshido/GraphQL Field classes.&lt;/li&gt;&#13;
                    &lt;li&gt;&lt;strong&gt;src/Type&lt;/strong&gt;: This direcotry stores Youshido/GraphQL Type classes.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;We will use Composer to manage our own classes' auto-loading, add following content to the bottom of&#13;
                    &lt;strong&gt;composer.json&lt;/strong&gt; file:&lt;/p&gt;&#13;
&#13;
                 &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
                    {&#13;
                    ...&#13;
                        "autoload"&#13;
                    :&#13;
                        {&#13;
                            "psr-4"&#13;
                        :&#13;
                            {&#13;
                                "StarTutorial\\"&#13;
                            :&#13;
                                "src"&#13;
                            }&#13;
                        }&#13;
                    }&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Run the following command from your command line interface to refresh Composer loader:&lt;/p&gt;&#13;
&#13;
                &lt;script&gt;composer dumpautoload&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Complete our fake repository classes by copying following content to their respective files:&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;src/Repository/ArticlesRepository.php&lt;/strong&gt;:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
namespace StarTutorial\Repository;&#13;
&#13;
class ArticlesRepository&#13;
{&#13;
    public static function findAll()&#13;
    {&#13;
        return [&#13;
            [&#13;
                'id' =&gt; 1,&#13;
                'title' =&gt; 'My First GraphQL API',&#13;
                'content' =&gt; 'It is all about GraphQL',&#13;
                'created' =&gt; new \DateTime('2017-02-24 11:20:10'),&#13;
                'author_id' =&gt; 1,&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 2,&#13;
                'title' =&gt; 'GraphQL History',&#13;
                'content' =&gt; 'GraphQL is created by Facebook',&#13;
                'created' =&gt; new \DateTime('2017-03-27 12:20:10'),&#13;
                'author_id' =&gt; 2&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 3,&#13;
                'title' =&gt; 'GraphQL vs Rest',&#13;
                'content' =&gt; 'GraphQL is a query language, whereas Rest is a protocol',&#13;
                'created' =&gt; new \DateTime('2017-04-30 13:20:10'),&#13;
                'author_id' =&gt; 2&#13;
            ]&#13;
        ];&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;src/Repository/AuthorsRepository.php&lt;/strong&gt;:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
namespace StarTutorial\Repository;&#13;
&#13;
&#13;
class AuthorsRepository&#13;
{&#13;
    public static function findAll()&#13;
    {&#13;
        return [&#13;
            [&#13;
                'id' =&gt; 1,&#13;
                'name' =&gt; 'Xu',&#13;
            ],&#13;
            [&#13;
                'id' =&gt; 2,&#13;
                'name' =&gt; 'Lee',&#13;
            ]&#13;
        ];&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. Reading an article with ID&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In a quick summary, GraphQL is a query language and&#13;
                    it works by defining a schema that describes how and what data can be queried by clients.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;There are two types of Operations in GraphQL:&lt;/p&gt;&#13;
&#13;
                &lt;ul&gt;&#13;
                    &lt;li&gt;Query: a read-only request that is not supposed to do any changes on the server.&lt;/li&gt;&#13;
                    &lt;li&gt;Mutation: a request that changes(mutate) data on the server and followed by a data fetch.&lt;/li&gt;&#13;
                &lt;/ul&gt;&#13;
&#13;
                &lt;p&gt;We are going to create a Query that will allow us to read an article with its ID.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;The first thing we need to do is to create an &lt;strong&gt;ArticleType&lt;/strong&gt; class as shown below:&lt;/p&gt;&#13;
                &lt;p&gt;src/Type/ArticleType.php:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
namespace StarTutorial\Type;&#13;
&#13;
&#13;
use Youshido\GraphQL\Type\NonNullType;&#13;
use Youshido\GraphQL\Type\Object\AbstractObjectType;&#13;
use Youshido\GraphQL\Type\Scalar\DateTimeType;&#13;
use Youshido\GraphQL\Type\Scalar\IntType;&#13;
use Youshido\GraphQL\Type\Scalar\StringType;&#13;
&#13;
class ArticleType extends AbstractObjectType&#13;
{&#13;
    public function build($config)&#13;
    {&#13;
        $config-&gt;addFields([&#13;
            'id' =&gt; new NonNullType(new IntType()),&#13;
            'title' =&gt; new StringType(),&#13;
            'content' =&gt; new StringType(),&#13;
            'created' =&gt; new DateTimeType(),&#13;
            'author_id' =&gt; new NonNullType(new IntType())&#13;
        ]);&#13;
    }&#13;
&#13;
}&#13;
&#13;
&lt;/script&gt;&#13;
                &lt;p&gt;Type classes in &lt;strong&gt;Youshido/GraphQL&lt;/strong&gt; define the fields and their values' types&#13;
                    that a Type possesses.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Next, we need to do is to create an &lt;strong&gt;ArticleField&lt;/strong&gt; class as shown below:&lt;/p&gt;&#13;
                &lt;p&gt;src/Field/ArticleField.php:&lt;/p&gt;&#13;
&lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
&#13;
namespace StarTutorial\Field;&#13;
&#13;
&#13;
use StarTutorial\Repository\ArticlesRepository;&#13;
use StarTutorial\Type\ArticleType;&#13;
use Youshido\GraphQL\Config\Field\FieldConfig;&#13;
use Youshido\GraphQL\Execution\ResolveInfo;&#13;
use Youshido\GraphQL\Field\AbstractField;&#13;
use Youshido\GraphQL\Type\Scalar\IntType;&#13;
&#13;
class ArticleField extends AbstractField&#13;
{&#13;
    public function getType()&#13;
    {&#13;
        return new ArticleType();&#13;
    }&#13;
&#13;
    public function build(FieldConfig $config)&#13;
    {&#13;
        $config-&gt;addArgument('id', new IntType());&#13;
    }&#13;
&#13;
    public function resolve($value, array $args, ResolveInfo $info)&#13;
    {&#13;
        $all = ArticlesRepository::findAll();&#13;
&#13;
        foreach ($all as $single) {&#13;
            if ($single['id'] == $args['id']) {&#13;
                return $single;&#13;
            }&#13;
        }&#13;
&#13;
        return null;&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Field classes in &lt;strong&gt;Youshido/GraphQL&lt;/strong&gt; will resolve users' request and respond&#13;
                    with data types defined above in Type classes. We also define acceptable arguments in Field classes.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Lastly, we will define a schema attached with &lt;strong&gt;ArticleField&lt;/strong&gt;. Meanwhile, we will create a simple&#13;
                request to our own schema right from PHP:&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Create a new file &lt;strong&gt;tutorial-introduction.php&lt;/strong&gt;:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
&#13;
    use StarTutorial\Field\ArticleField;&#13;
    use Youshido\GraphQL\Execution\Processor;&#13;
    use Youshido\GraphQL\Schema\Schema;&#13;
    use Youshido\GraphQL\Type\Object\ObjectType;&#13;
&#13;
    require_once 'vendor/autoload.php';&#13;
&#13;
    $processor = new Processor(new Schema([&#13;
        'query' =&gt; new ObjectType([&#13;
            'name' =&gt; 'RootQueryType',&#13;
            'fields' =&gt; [&#13;
                new ArticleField()&#13;
            ]&#13;
        ]),&#13;
    ]));&#13;
&#13;
    $processor-&gt;processPayload('{ article(id:2){id,title} }');&#13;
&#13;
    echo '&lt;pre&gt;';&#13;
    echo json_encode($processor-&gt;getResponseData()) . "\n";&#13;
    echo '&lt;pre&gt;';&#13;
&#13;
&lt;/script&gt;&#13;
&#13;
&lt;p&gt;Access the page from the browser of your choice via the URL http://your-local-php-server/tutorial-introduction.php. &lt;/p&gt;&#13;
&lt;p&gt;You should expect a JSON output as shown below if you have followed this tutorial correctly: &lt;/p&gt;&#13;
&lt;script type="syntaxhighlighter" class="brush: text"&gt;&#13;
{&#13;
"data": {&#13;
    "article": {&#13;
        "id": 2,&#13;
        "title": "GraphQL History"&#13;
        }&#13;
    }&#13;
}&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Try to change the ID argument or add other fields, see how GraphQL gives you exactly what you ask.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
                &lt;p&gt;&#13;
                    Now we have set our goal clearly and had our first simple GraphQL end point.&#13;
                    Next tutorial, we will implement a Field that can resolve a list of articles and explain how we&#13;
                    can accomplish pagination in &lt;strong&gt;Youshido/GraphQL&lt;/strong&gt;.&#13;
                    &lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Wed, 03 May 2017 06:19:04 +0000</pubDate></item><item><title>How to integrate Facebook login with CakePHP 3</title><link>https://www.startutorial.com/articles/view/how-to-integrate-facebook-login-with-cakephp-3</link><guid>https://www.startutorial.com/articles/view/how-to-integrate-facebook-login-with-cakephp-3<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    &lt;a href="https://www.startutorial.com/articles/view/how-to-build-facebook-login-using-cakephp-facebook-login-plugin" target="_blank"&gt;Previously&lt;/a&gt;,&#13;
                    we have learned how to integrate Facebook login using a plugin called Facebook Login. A lot of things have changed since then,&#13;
                    include Facebook SDK and the maintenance of Facebook Login plugin. It has become obviously that we need&#13;
                    a new way to integrate Facebook login with CakePHP application.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;In this tutorial, we will show you how to integrate Facebook login with CakePHP 3 application using another CakePHP plugin.&lt;/p&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Setup Users Table&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Setup CakePHP HybridAuth Plugin&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Setup Controller&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;Setup Event Listener&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec5"&gt;Setup View&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec6"&gt;The End&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Setup Users Table&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;A database table is required to store users' information such as email, password and so on.&#13;
                    To keep it simple, we will create a very simple &lt;strong&gt;users&lt;/strong&gt; table. It contains&#13;
                fields required to demonstrate Facebook login only.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: sql"&gt;&#13;
CREATE TABLE IF NOT EXISTS `users` (&#13;
  `id` int(11) NOT NULL AUTO_INCREMENT,&#13;
  `email` varchar(250) NOT NULL,&#13;
  `password` varchar(250) NOT NULL,&#13;
  PRIMARY KEY (`id`)&#13;
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    If your users table has fields, as shown above, it should work for this tutorial.&#13;
                    You can use your own users table in that case.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Setup CakePHP HybridAuth Plugin&lt;/h6&gt;&#13;
                &lt;p&gt;&#13;
                    &lt;a href="https://github.com/ADmad/CakePHP-HybridAuth" target="_blank"&gt;CakePHP HybridAuth Plugin&lt;/a&gt;&#13;
                    is a wrapper around &lt;a href="http://hybridauth.github.io/hybridauth/" target="_blank"&gt;HybridAuth library.&lt;/a&gt;&#13;
                    HybridAuth library builds an abstraction layer on top of various social login.&#13;
                    Which makes the task of integrating social login a breeze.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Install&lt;/strong&gt;&lt;/p&gt;&#13;
                &lt;p&gt;Install CakePHP HybridAuth using Composer:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
composer require --prefer-dist admad/cakephp-hybridauth&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Load&lt;/strong&gt;&lt;/p&gt;&#13;
                &lt;p&gt;Load the plugin using Bake command:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
bin/cake plugin load ADmad/HybridAuth -b -r&#13;
                &lt;/script&gt;&#13;
                &lt;p&gt;This will basically append a line of code as shown below to your app's config/bootstrap.php.&#13;
                So you can do it manually if you wish to.&#13;
                &lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
Plugin::load('ADmad/HybridAuth', ['bootstrap' =&gt; true, 'routes' =&gt; true]);&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;&lt;strong&gt;Configuration&lt;/strong&gt;&lt;/p&gt;&#13;
                &lt;p&gt;Make a config file config/hybridauth.php:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
use Cake\Core\Configure;&#13;
&#13;
return [&#13;
    'HybridAuth' =&gt; [&#13;
        'providers' =&gt; [&#13;
            'Facebook' =&gt; [&#13;
                'enabled' =&gt; true,&#13;
                'keys' =&gt; [&#13;
                    'id' =&gt; 'facebook-id',&#13;
                    'secret' =&gt; 'facebook-secret-key'&#13;
                ],&#13;
                'scope' =&gt; 'email, public_profile'&#13;
            ]&#13;
        ]&#13;
    ],&#13;
];&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Replace "facebook-id" and "facebook-secret-key" with your own.&#13;
                    If you do not know where to find them, refer to&#13;
                    &lt;a href="http://stackoverflow.com/a/39937114/406358" target="_blank"&gt;this link&lt;/a&gt;.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;In some case, you might wonder if you could place this configure values in other config files.&#13;
                    The answer is yes. As long as you make sure &lt;strong&gt;HybridAuth&lt;/strong&gt; config values exist.&#13;
                This plugin will happily pick them up.&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. Setup Controller&lt;/h6&gt;&#13;
                &lt;p&gt;Next, we need a controller action to allow users to log in.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Create src/Controller/UsersController:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt?php&#13;
namespace App\Controller;&#13;
&#13;
use Cake\Event\Event;&#13;
&#13;
class UsersController extends AppController&#13;
{&#13;
    public function beforeFilter(Event $event)&#13;
    {&#13;
        parent::beforeFilter($event);&#13;
&#13;
        $this-&gt;Auth-&gt;allow();&#13;
&#13;
    }&#13;
&#13;
&#13;
    public function login()&#13;
    {&#13;
        if ($this-&gt;request-&gt;is('post') || $this-&gt;request-&gt;query('provider')) {&#13;
            $user = $this-&gt;Auth-&gt;identify();&#13;
            if ($user) {&#13;
                $this-&gt;Auth-&gt;setUser($user);&#13;
                return $this-&gt;redirect($this-&gt;Auth-&gt;redirectUrl());&#13;
            }&#13;
            $this-&gt;Flash-&gt;error(__('Invalid username or password, try again'));&#13;
        }&#13;
    }&#13;
&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;A caveat here. Do not place any special logic after the $this-&gt;Auth-&gt;identify() call. Because&#13;
                this method is not guaranteed to return, it redirects users away to the social site for authentication.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;One more step for the controller work. Add CakePHP HybridAuth's authentication handlers to our application's&#13;
                auth component.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Add the handler in app/AppController.php&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;php&#13;
class AppController extends Controller&#13;
{&#13;
&#13;
    public function initialize()&#13;
    {&#13;
        parent::initialize();&#13;
        $this-&gt;loadComponent('Auth', [&#13;
            'authenticate' =&gt; [&#13;
                'Form' =&gt; [&#13;
                    'fields' =&gt; ['username' =&gt; 'email']&#13;
                ],&#13;
                'ADmad/HybridAuth.HybridAuth' =&gt; [&#13;
                    // All keys shown below are defaults&#13;
                    'fields' =&gt; [&#13;
                        'provider' =&gt; 'provider',&#13;
                        'openid_identifier' =&gt; 'openid_identifier',&#13;
                        'email' =&gt; 'email'&#13;
                    ],&#13;
                    'profileModel' =&gt; 'ADmad/HybridAuth.SocialProfiles',&#13;
                    'profileModelFkField' =&gt; 'user_id',&#13;
                    'userModel' =&gt; 'Users',&#13;
                    'hauth_return_to' =&gt; [&#13;
                        'controller' =&gt; 'Users',&#13;
                        'action' =&gt; 'socail_login',&#13;
                        'prefix' =&gt; false,&#13;
                        'plugin' =&gt; false&#13;
                    ]&#13;
                ]&#13;
            ]&#13;
        ]);&#13;
    }&#13;
&#13;
    // Your other controller code&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. Setup Event Listener&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    The event HybridAuth.newUser will be fired if CakePHP HybridAuth plugin could not find a user record&#13;
                    from the users table. So an event listener is needed to create a brand new user record.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Add an event listener in app/AppController.php&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;php&#13;
&#13;
class AppController extends Controller&#13;
{&#13;
&#13;
    public function beforeFilter(Event $event)&#13;
    {&#13;
        \Cake\Event\EventManager::instance()-&gt;on('HybridAuth.newUser', [$this, 'createUser']);&#13;
    }&#13;
&#13;
    public function createUser(\Cake\Event\Event $event) {&#13;
	    // Entity representing record in social_profiles table&#13;
	    $profile = $event-&gt;data()['profile'];&#13;
&#13;
	    $user = $this-&gt;newEntity([&#13;
	    	'email' =&gt; $profile-&gt;email,&#13;
	    	'password' =&gt; time()&#13;
    	]);&#13;
	    $user = $this-&gt;save($user);&#13;
&#13;
	    if (!$user) {&#13;
	        throw new \RuntimeException('Unable to save new user');&#13;
	    }&#13;
&#13;
	    return $user;&#13;
	}&#13;
&#13;
&#13;
    // Your other controller code&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Note that we created a random password using current timestamp. This way, we can avoid having&#13;
                an empty password.&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec5"&gt;5. Setup View&lt;/h6&gt;&#13;
                &lt;p&gt;There is not much to setup in a view, besides understanding how to create a login link.&lt;/p&gt;&#13;
                &lt;p&gt;In HybridAuth library, a social login URL follows current format:&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;http://your-website-url/login&lt;strong&gt;?provider=facebook&lt;/strong&gt;&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;In CakePHP, we can generate the link above with HtmlHelper:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$this-&gt;Html-&gt;link(&#13;
 'Login with Facebook',&#13;
 ['controller' =&gt; 'Users', 'action' =&gt; 'login', '?' =&gt; ['provider' =&gt; 'Facebook']]&#13;
);&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;For now, your application should be integrated with Facebook login.&#13;
                    Try it out and enjoy the benefits it brings for your users.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec6"&gt;6. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Mon, 01 May 2017 15:23:36 +0000</pubDate></item><item><title>Preview email with DebugKit in CakePHP 3</title><link>https://www.startutorial.com/articles/view/preview-email-with-debugkit-in-cakephp-3</link><guid>https://www.startutorial.com/articles/view/preview-email-with-debugkit-in-cakephp-3<isPermaLink>true</isPermaLink></guid><description>&lt;blockquote&gt;&#13;
                    The ability to preview an email's look and feel during development is&#13;
                    a huge time saver for developers.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;The de-facto CakePHP development tool DebugKit, shipped along with CakePHP 3, already provides&#13;
                    a way to preview an email during development. It renders the email right inside the browser so&#13;
                    that we can edit the email view and refresh the browser to get instant feedback. &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;In this tutorial, we introduce you DebugKit mail panel, a way to preview your email&#13;
                    during development without actually sending it.&lt;/p&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Installation&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Create an Email with Mailer class&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Create MailPreview class&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The End&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Installation&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Email preview only works for CakePHP 3.1+. So you are out of luck if you are in an older version.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Install DebugKit 3+ via composer:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
composer require --dev cakephp/debug_kit "~3.0"&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Load the plugin via Bake command:&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
                bin/cake plugin load DebugKit&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Now you should be able to see DebugKit toolbar showing at the bottom of your application.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;If for some reasons, it does not show up. Run the command below, it is to make sure DebugKit's&#13;
                    assets(js/css files) can be loaded properly.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
                bin/cake plugin assets symlink&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Create an Email with Mailer&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Email preview is implemented with MailPreview class and MailPreview integrates with CakePHPâ€™s Mailer class.&#13;
                Your email needs to be implemented using Mailer class in order to get the preview feature.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Create an email using the Mailer class under src/Mailer/UserMailer:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt&gt;?php&#13;
namespace App\Mailer;&#13;
&#13;
use Cake\Mailer\Mailer;&#13;
&#13;
class UserMailer extends Mailer&#13;
{&#13;
    public function welcome($user)&#13;
    {&#13;
        return $this // Returning the chain is a good idea :)&#13;
        -&gt;to($user-&gt;email)&#13;
            -&gt;subject(sprintf("Welcome %s", $user-&gt;name))&#13;
            -&gt;template("welcome_mail") // By default template with same name as method name is used.&#13;
            -&gt;layout("custom")&#13;
            -&gt;set(["user" =&gt; $user]);&#13;
    }&#13;
}&#13;
                    &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;If you are not sure how to use Mailer class, take a look at&#13;
                    &lt;a target="_blank" href="https://book.cakephp.org/3.0/en/core-libraries/email.html#creating-reusable-emails"&gt;https://book.cakephp.org/3.0/en/core-libraries/email.html#creating-reusable-emails&lt;/a&gt;.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec3"&gt;4. Create MailPreview&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Create a MailPreview class for UserMailer under src/Mailer/Preview/UserMailPreview.php:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;?php&#13;
namespace App\Mailer\Preview;&#13;
&#13;
use DebugKit\Mailer\MailPreview;&#13;
&#13;
class UserMailPreview extends MailPreview&#13;
{&#13;
    public function welcome()&#13;
    {&#13;
        $this-&gt;loadModel("Users");&#13;
        $user = $this-&gt;Users-&gt;find()-&gt;first();&#13;
        return $this-&gt;getMailer("User")&#13;
            -&gt;welcome($user)&#13;
            -&gt;set(["activationToken" =&gt; "dummy-token"]);&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;That's all the steps to get the email preview from DebugKit.&#13;
                Now refresh your browser and you should be able to see your emails showing up at the preview panel: &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    &lt;img src="https://www.startutorial.com/img/cakephp-3-email-preview.png" class="thumbnail"&gt;&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Mon, 01 May 2017 15:17:16 +0000</pubDate></item><item><title>Your first GraphQL API - Nested Queries</title><link>https://www.startutorial.com/articles/view/your-first-graphql-api-nested-queries</link><guid>https://www.startutorial.com/articles/view/your-first-graphql-api-nested-queries<isPermaLink>true</isPermaLink></guid><description>                &lt;blockquote&gt;&#13;
                    Typically our database is designed with some relationships.&#13;
                    When retrieving data from our GraphQL, we would want them to present in a relationship hierarchy as well.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;In this tutorial, we will learn how to build nested queries using &lt;strong&gt;Youshido/GraphQL&lt;/strong&gt;. &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;In our blog example, there is a series of articles and each article belongs to an author.&#13;
                When retrieving articles' data, it makes more sense to fetch belonging author's data as well instead of&#13;
                "author_id".&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Add AuthorType.php&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Add AuthorField.php&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Modify ArticleField.php&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Add AuthorType.php&lt;/h6&gt;&#13;
                &lt;p&gt;Apparently, we need AuthorType in order to resolve the type.&lt;/p&gt;&#13;
                &lt;p&gt;Add &lt;strong&gt;src/Type/AuthorType.php&lt;/strong&gt;&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
&amp;lt;?php&#13;
namespace StarTutorial\Type;&#13;
&#13;
use Youshido\GraphQL\Type\NonNullType;&#13;
use Youshido\GraphQL\Type\Object\AbstractObjectType;&#13;
use Youshido\GraphQL\Type\Scalar\IntType;&#13;
use Youshido\GraphQL\Type\Scalar\StringType;&#13;
&#13;
class AuthorType extends AbstractObjectType&#13;
{&#13;
    public function build($config)&#13;
    {&#13;
        $config-&gt;addFields([&#13;
            'id' =&gt; new NonNullType(new IntType()),&#13;
            'name' =&gt; new StringType()&#13;
        ]);&#13;
    }&#13;
}&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;As we can see, it is a super simple type with an id(integer) and name(string) fields.&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Add AuthorField.php&lt;/h6&gt;&#13;
                &lt;p&gt;We will use AuthorField to resolve the request.&lt;/p&gt;&#13;
                &lt;p&gt;Add &lt;strong&gt;src/Field/AuthorField.php&lt;/strong&gt;&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&amp;lt;?php&#13;
namespace StarTutorial\Field;&#13;
&#13;
use StarTutorial\Repository\AuthorsRepository;&#13;
use StarTutorial\Type\AuthorType;&#13;
use Youshido\GraphQL\Execution\ResolveInfo;&#13;
use Youshido\GraphQL\Field\AbstractField;&#13;
&#13;
class AuthorField extends AbstractField&#13;
{&#13;
    public function getType()&#13;
    {&#13;
        return new AuthorType();&#13;
    }&#13;
&#13;
    public function resolve($value, array $args, ResolveInfo $info)&#13;
    {&#13;
        $authorId = $value['author_id'];&#13;
&#13;
        $all = AuthorsRepository::findAll();&#13;
&#13;
        foreach ($all as $single) {&#13;
            if ($single['id'] == $authorId) {&#13;
                return $single;&#13;
            }&#13;
        }&#13;
&#13;
        return null;&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Let's take a close look at the &lt;strong&gt;resolve&lt;/strong&gt; method.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;When getting the $authorId, we fetch it directly from the $value variable as shown below:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
                    $authorId = $value['author_id'];&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    This is because $value is configured to contain values from the parent.&#13;
                    Which is article is our case. And because we know article will return an &lt;strong&gt;author_id&lt;/strong&gt;,&#13;
                    we fetch it directly from $value variable.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;The rest of the code is self-explanatory, we find the author that article belongs to using our&#13;
                fake repository and return it.&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. Modify ArticleField.php&lt;/h6&gt;&#13;
                &lt;p&gt;We are almost done. The last piece is to modify ArticleField.php to wire ArticleType and AuthorType up.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;To do this, open &lt;strong&gt;src/Type/ArticleType.php&lt;/strong&gt;. And change &lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
                    'author_id' =&gt; new NonNullType(new IntType())&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;to&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
                    'author' =&gt; new AuthorField()&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Our final &lt;strong&gt;src/Type/ArticleType.php&lt;/strong&gt; file looks like this after the modification:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&amp;lt;?php&#13;
namespace StarTutorial\Type;&#13;
&#13;
use StarTutorial\Field\AuthorField;&#13;
use Youshido\GraphQL\Type\NonNullType;&#13;
use Youshido\GraphQL\Type\Object\AbstractObjectType;&#13;
use Youshido\GraphQL\Type\Scalar\DateTimeType;&#13;
use Youshido\GraphQL\Type\Scalar\IntType;&#13;
use Youshido\GraphQL\Type\Scalar\StringType;&#13;
&#13;
class ArticleType extends AbstractObjectType&#13;
{&#13;
    public function build($config)&#13;
    {&#13;
        $config-&gt;addFields([&#13;
            'id' =&gt; new NonNullType(new IntType()),&#13;
            'title' =&gt; new StringType(),&#13;
            'content' =&gt; new StringType(),&#13;
            'created' =&gt; new DateTimeType(),&#13;
            'author' =&gt; new AuthorField()&#13;
        ]);&#13;
    }&#13;
&#13;
}&#13;
&#13;
&lt;/script&gt;&#13;
&#13;
&#13;
                &lt;p&gt;In the first tutorial, we are getting articles data using a query similar to: &lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
{ article(id:2){id,title,author_id} }&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Now we can get full author data using:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
{ article(id:2){id,title,author{name}} }&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                The magic here is that, if you do not ask for author's data.&#13;
                    The resolve method(&lt;strong&gt;AuthorField::resolve&lt;/strong&gt;) will never be called.&#13;
                The &lt;strong&gt;Youshido/GraphQL&lt;/strong&gt; library takes care of the job of figuring out which resolve&#13;
                methods to call.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;&#13;
</description><pubDate>Thu, 27 Apr 2017 06:46:54 +0000</pubDate></item><item><title>PHPUnit Tip - Access Private Properties of an Object via Closure</title><link>https://www.startutorial.com/articles/view/phpunit-tip-access-private-properties-of-an-object-via-closure</link><guid>https://www.startutorial.com/articles/view/phpunit-tip-access-private-properties-of-an-object-via-closure<isPermaLink>true</isPermaLink></guid><description>     &lt;blockquote&gt;&#13;
                    In this tutorial, we share a tip on how we can access a private property of an object without using&#13;
                    getter/setter methods.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;Sometimes, when writing out tests, to inspect the private properties of our testing class, we&#13;
                have no choice but using setter/getter methods. There setter/getter methods exist solely for the purpose&#13;
                of assisting the tests, which feel wrong to us.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Recently we came across a great article at https://markbakeruk.net/2017/03/05/closures-anonymous-classes-test-mocking-1/. Which&#13;
                shares how we can use Closure to access the private properties of an object. &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;In this tutorial, we would like to share how we can use Closure in our PHPUnit tests:&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Disclaimer:&#13;
                    the code samples in this tutorial are for purpose of demonstrating the tactic, they might not&#13;
                    be the perfect testing code.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;About PHP Closure&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Get Private Properties without Getter&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Set Mock without Setter&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. About PHP Closure&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;In simple terms, a Closure is an anonymous function, but it can access variables outside the scope that it was created.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Most of people have used Closure before, for example, using it in &lt;strong&gt;array_filter&lt;/strong&gt;.&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$genius = 'Addison';&#13;
&#13;
$users = ['Addison', 'Benjamin', 'Calvin'];&#13;
&#13;
$callback = function($user) use ($genius) {&#13;
    return $user == $genius;&#13;
};&#13;
&#13;
$answer = array_filter($users, $callback);&#13;
&#13;
echo implode('',$answer);&#13;
&#13;
// Output:&#13;
// Addison&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;However, most of the people are not aware that we can do this:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Person&#13;
{&#13;
    private $name;&#13;
&#13;
    public function __construct($name)&#13;
    {&#13;
        $this-&gt;name = $name;&#13;
    }&#13;
&#13;
    public function callMe()&#13;
    {&#13;
        return $this-&gt;name;&#13;
    }&#13;
&#13;
}&#13;
&#13;
$addison = new Person('Addison');&#13;
&#13;
echo $addison-&gt;callMe();&#13;
// Output:&#13;
// Addison&#13;
&#13;
$changePropertyClosure = function () {&#13;
    $this-&gt;name = 'Benjamin';&#13;
};&#13;
&#13;
$doChangePropertyClosure = $changePropertyClosure-&gt;bindTo($addison, get_class($addison));&#13;
$doChangePropertyClosure();&#13;
&#13;
echo $addison-&gt;callMe();&#13;
// Output:&#13;
// Benjamin&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;Pay attention to how Addison's name is changed by &lt;strong&gt;$changePropertyClosure&lt;/strong&gt; to Benjamin,&#13;
                though the &lt;strong&gt;name&lt;/strong&gt; is a private property of &lt;strong&gt;Person&lt;/strong&gt; class.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;The uncommon method of Closure class we have shown above is &lt;strong&gt;Closure::bindTo&lt;/strong&gt;.&#13;
                It allows us to duplicate the closure with a new bound object and class scope. You can check out the method&#13;
                    details at http://php.net/manual/en/closure.bindto.php.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    In simple terms, we can use Closure's method &lt;strong&gt;bindTo&lt;/strong&gt; to access private properties of any classes.&#13;
                    With that in mind, let's move on to specific use cases.&#13;
                &lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Get Private Properties without Getter&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Imagine we have an object which has getter methods to return private properties,&#13;
                    but these are only used by the tests to check the state of the object and are never called,&#13;
                    or intended to be called, by the client.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Person&#13;
{&#13;
    private $name;&#13;
&#13;
    public function __construct($name)&#13;
    {&#13;
        $this-&gt;name = $name;&#13;
    }&#13;
&#13;
    public function hide()&#13;
    {&#13;
        $this-&gt;name = 'anonymous';&#13;
    }&#13;
&#13;
    public function getName()&#13;
    {&#13;
        return $this-&gt;name;&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;In the code above, we have a getter method &lt;strong&gt;getName()&lt;/strong&gt;. Its sole purpose is&#13;
                to get the private property &lt;strong&gt;$name&lt;/strong&gt; for out test. So that we can write a test for&#13;
                the &lt;strong&gt;hide()&lt;/strong&gt; method.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;By using Closure, we can actually eliminate the &lt;strong&gt;getName()&lt;/strong&gt; method.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class PersonTest extends PHPUnit_Framework_TestCase&#13;
{&#13;
    public function testHide()&#13;
    {&#13;
        // Arrange&#13;
        $that = $this;&#13;
        $addison = new Person('Addison');&#13;
        $assertPropertyClosure = function ()  use ($that){&#13;
            $that-&gt;assertEquals('anonymous', $this-&gt;name);&#13;
        };&#13;
        $doAssertPropertyClosure = $assertPropertyClosure-&gt;bindTo($addison, get_class($addison));&#13;
&#13;
        // Act&#13;
        $addison-&gt;hide();&#13;
&#13;
        // Assert&#13;
        $doAssertPropertyClosure();&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;As you can see from the code above. The Closure &lt;strong&gt;$assertPropertyClosure&lt;/strong&gt; is able to&#13;
                look inside the &lt;strong&gt;Person&lt;/strong&gt; object and get the private property &lt;strong&gt;$name&lt;/strong&gt;&#13;
                    using &lt;strong&gt;$this&lt;/strong&gt; context.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Another nice trick we used is that since &lt;strong&gt;$this&lt;/strong&gt; has been bound to the bound object, we just assigned it&#13;
                    to a new variable &lt;strong&gt;$that&lt;/strong&gt;, so that we can still use the assertion inside the Closure.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. Set Mock without Setter&lt;/h6&gt;&#13;
                &lt;p&gt;Imagine we have an object which has a setter method to set collaborator,&#13;
                    but this setter is only used by the tests to set a mock of the collaborator, it is not used by the client.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class Phone&#13;
{&#13;
    function dial($number)&#13;
    {&#13;
&#13;
    }&#13;
}&#13;
&#13;
class Person&#13;
{&#13;
    private $phone;&#13;
&#13;
    public function __construct()&#13;
    {&#13;
        $this-&gt;phone = new Phone;&#13;
    }&#13;
&#13;
    public function call($number)&#13;
    {&#13;
        $this-&gt;phone-&gt;dial($number);&#13;
    }&#13;
&#13;
    public function setPhone($phone)&#13;
    {&#13;
        $this-&gt;phone = $phone;&#13;
    }&#13;
&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;In the code above, we have a setter method &lt;strong&gt;setPhone()&lt;/strong&gt;. Its sole purpose is&#13;
                    to set the private property &lt;strong&gt;$phone&lt;/strong&gt; for out test.&#13;
                    So that we can write a test for &lt;strong&gt;call()&lt;/strong&gt; method.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;By using Closure, we can actually eliminate the &lt;strong&gt;setPhone()&lt;/strong&gt; method.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
class PersonTest extends PHPUnit_Framework_TestCase&#13;
{&#13;
    public function testCall()&#13;
    {&#13;
        // Arrange&#13;
        $addison = new Person();&#13;
        $mockPhone = $this-&gt;getMockBuilder(Phone::class)-&gt;getMock();&#13;
        $mockPhone-&gt;expects($this-&gt;exactly(1))-&gt;method('dial');&#13;
        $setPhoneClosure = function ()  use ($mockPhone){&#13;
            $this-&gt;phone = $mockPhone;&#13;
        };&#13;
        $doSetPhoneClosure = $setPhoneClosure-&gt;bindTo($addison, get_class($addison));&#13;
        $doSetPhoneClosure();&#13;
&#13;
        // Act&#13;
        $addison-&gt;call(93803212);&#13;
    }&#13;
}&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;As you can see from the code above. The Closure &lt;strong&gt;$setPhoneClosure&lt;/strong&gt; is able to&#13;
                    look inside the &lt;strong&gt;Person&lt;/strong&gt; object and set the private property &lt;strong&gt;$phone&lt;/strong&gt;&#13;
                    using &lt;strong&gt;$this&lt;/strong&gt; context.&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;&#13;
</description><pubDate>Tue, 28 Mar 2017 05:51:15 +0000</pubDate></item><item><title>Quick tip on working with timezone in CakePHP 3</title><link>https://www.startutorial.com/articles/view/quick-tip-on-working-with-timezone-in-cakephp-3</link><guid>https://www.startutorial.com/articles/view/quick-tip-on-working-with-timezone-in-cakephp-3<isPermaLink>true</isPermaLink></guid><description>   &lt;blockquote&gt;&#13;
                    In a recent project, we need to allow users to set start and end time of their&#13;
                    events and the application is targeted worldwide clients, which leads us to discover some tips on&#13;
                    working with timezone in CakePHP 3.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;In this post, we share some tips we have learned.&lt;/p&gt;&#13;
&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Set Application Timezone to UTC&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Convert Inputs to UTC Base&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Convert Database DataTime to a User's Timezone&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;The End&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Set Application Timezone to UTC&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;If you are working on an application that is for a single timezone,&#13;
                    then you can happily set the timezone to that timezone.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;However if your application is across time zones,&#13;
                    to make time calculation and conversions easier, you should set the application's timezone to UTC&#13;
                    (If you need a review of UTC,&#13;
                    &lt;a href="https://www.timeanddate.com/time/aboututc.html" target="_blank"&gt;here you go&lt;/a&gt;). &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;We can do that from &lt;strong&gt;config/bootstrap.php&lt;/strong&gt; file:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;date_default_timezone_set('UTC');&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;This will set our application's default timezone to UTC. Any method calls to DateTime instance will&#13;
                    take UTC as the timezone. This means all datetime database columns will use UTC-based time.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Convert Inputs to UTC Base&lt;/h6&gt;&#13;
                &lt;p&gt;&#13;
                    The whole idea of using UTC is to keep times in database in sync, it becomes the single point of truth.&#13;
                    When we need to do stuff like calculation and conversions, we can safely assume its base is UTC.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;Therefore, when saving time to database, we need to convert users' input which is based on&#13;
                    their own timezone to UTC, in order to keep our database as the single point of truth.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;CakePHP 3 uses &lt;strong&gt;Cake\I18n\Time&lt;/strong&gt; as the class for handling time.&#13;
                    We can use it to do the conversion. For example:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
$timeForDatabase = (new Time($userInputTime, 'America/New_York'))-&gt;setTimezone('UTC');&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. Convert Database DataTime to a User's Timezone&lt;/h6&gt;&#13;
                &lt;p&gt;When displaying the time from the database to user, we need to convert it back to user's timezone.&#13;
                    Otherwise, the user will definitely be confused.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;We do it as simply as:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
$timeForUser = $timeFromDatabase-&gt;setTimezone('America/New_York');&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;CakePHP 3 ORM will return &lt;strong&gt;Cake\I18n\Time&lt;/strong&gt; instances for DateTime columns. Thus&#13;
                we do not have to instantiate it.&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. The End&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Tue, 28 Mar 2017 05:49:28 +0000</pubDate></item><item><title>Dealing with date range</title><link>https://www.startutorial.com/articles/view/dealing-with-date-range</link><guid>https://www.startutorial.com/articles/view/dealing-with-date-range<isPermaLink>true</isPermaLink></guid><description>  &lt;blockquote&gt;&#13;
                    In this tutorial, we walk through a few different scenarios of using &lt;strong&gt;league/period&lt;/strong&gt;.&#13;
                    The package &lt;strong&gt;league/period&lt;/strong&gt; is from PHP League and its purpose is to make handling&#13;
                    date range in PHP easier for developers.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Installing package&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Checking if a date falls in between a date range&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Checking if a date falls in between a date range&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;Checking if a date range falls in between another date range&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec5"&gt;Checking if two dates can form a valid date range&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec6"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Installing package&lt;/h6&gt;&#13;
                &lt;p&gt;First thing first, let's install the &lt;strong&gt;league/period&lt;/strong&gt; using composer as normal:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;composer require league/period&lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Checking if a date falls in between a date range&lt;/h6&gt;&#13;
                &lt;p&gt;If you have a $startDate and $endDate, how can you check if a date given by the user falls within&#13;
                    that range?&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;For example, if we have dates as shown below:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
$startDate = '2009-06-17';&#13;
$endDate = '2009-09-05';&#13;
$dateFromUser = '2009-08-28';&#13;
&#13;
&#13;
&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;We can use the method &lt;strong&gt;contains()&lt;/strong&gt; of &lt;strong&gt;Period&lt;/strong&gt; class to accomplish&#13;
                    that:&lt;/p&gt;&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. Returning all dates between two dates in an array&lt;/h6&gt;&#13;
                &lt;p&gt;Given a date range between $startDate and $endDate, how can you get all dates between these two dates&#13;
                    in an array?&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;For example, if we have dates as shown below:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
$startDate = '2009-06-17';&#13;
$endDate = '2009-09-05';&#13;
&#13;
&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;We can use the method &lt;strong&gt;getDatePeriod()&lt;/strong&gt; of &lt;strong&gt;Period&lt;/strong&gt; class to accomplish&#13;
                    that:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
$startDate = '2009-06-17';&#13;
$endDate = '2009-06-25';&#13;
&#13;
$period = new Period($startDate, $endDate);&#13;
foreach ($period-&gt;getDatePeriod('1 DAY') as $day) {&#13;
    var_dump($day-&gt;format('Y-m-d'));&#13;
}&#13;
// Output&#13;
//string(10) "2009-06-17"&#13;
//string(10) "2009-06-18"&#13;
//string(10) "2009-06-19"&#13;
//string(10) "2009-06-20"&#13;
//string(10) "2009-06-21"&#13;
//string(10) "2009-06-22"&#13;
//string(10) "2009-06-23"&#13;
//string(10) "2009-06-24"&#13;
&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. Checking if a date range falls in between another date range&lt;/h6&gt;&#13;
                &lt;p&gt;Given a date range between $startDate and $endDate:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
$startDate = '2009-06-17';&#13;
$endDate = '2009-09-05';&#13;
&#13;
&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;How can you verify if the dates below are in the range of the date range above?&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
$myStartDate = '2009-07-17';&#13;
$myEndDate = '2009-08-05';&#13;
&#13;
&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;We can use the method &lt;strong&gt;contains()&lt;/strong&gt; of &lt;strong&gt;Period&lt;/strong&gt; class to accomplish&#13;
                    that:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
$startDate = '2009-06-17';&#13;
$endDate = '2009-09-05';&#13;
&#13;
$myStartDate = '2009-07-17';&#13;
$myEndDate = '2009-08-05';&#13;
&#13;
$periodOne = new Period($startDate, $endDate);&#13;
$periodTwo = new Period($myStartDate, $myEndDate);&#13;
var_dump($periodOne-&gt;contains($periodTwo));&#13;
// Output&#13;
// bool(true)&#13;
&#13;
&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec5"&gt;5. Checking if two dates can form a valid date range&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;Suppose you accept two user inputs $startDate and $endDate from a form. How do you valid if&#13;
                    these two dates can form a valid date range. Normal Dates comparison would work, but it requires&#13;
                    you&#13;
                    to write your custom objects to handle that validation elegantly.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;p&gt;We can use &lt;strong&gt;Period&lt;/strong&gt; class since it already handles those validations for us. It will&#13;
                    make sure&#13;
                    it is a valid date range upon instantiation of a &lt;strong&gt;Period&lt;/strong&gt; instance.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: bash"&gt;&#13;
$startDate = '2009-06-17';&#13;
$endDate = '2009-09-05';&#13;
$period = new Period($endDate, $startDate);&#13;
// Output&#13;
// Fatal error: Uncaught exception 'LogicException' with message 'The ending datepoint must be greater or equal to the starting datepoint'&#13;
&lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec6"&gt;6. The end&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Mon, 20 Feb 2017 00:00:43 +0000</pubDate></item><item><title>Markdown Processing in PHP</title><link>https://www.startutorial.com/articles/view/markdown-processing-in-php</link><guid>https://www.startutorial.com/articles/view/markdown-processing-in-php<isPermaLink>true</isPermaLink></guid><description>   &lt;blockquote&gt;&#13;
                    &lt;a href="http://daringfireball.net/projects/markdown/" target="_blank"&gt;Markdown&lt;/a&gt; is a&#13;
                    text-to-HTML conversion tool for web writers. It has gained its deserved popularity after its&#13;
                    introduction on 2004. Markdown allows you to write text while providing a format in an easy and&#13;
                    clean way.&#13;
                &lt;/blockquote&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Though it is developed by Perl, it has been ported to different languages such as PHP.&#13;
                    In this tutorial, we will show you how to parse markdown in PHP.&#13;
                    There is already a library &lt;strong&gt;&lt;a href="https://github.com/thephpleague/commonmark"&#13;
                                                          target="_blank"&gt;league/commonmark&lt;/a&gt;&lt;/strong&gt; developed&#13;
                    by PHP League and it supports full &lt;a href="http://commonmark.org/" target="_blank"&gt;CommonMark&lt;/a&gt;&#13;
                    spec. We will be using this package across the tutorial.&#13;
                &lt;/p&gt;&#13;
&#13;
                &lt;h2 id="top"&gt;Table Of Content&lt;/h2&gt;&#13;
&#13;
                &lt;ol class="well"&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec1"&gt;Processing headers&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec2"&gt;Processing lists&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec3"&gt;Processing image&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec4"&gt;Processing table&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
&#13;
                    &lt;li&gt;&#13;
                        &lt;a href="#sec5"&gt;The end&lt;/a&gt;&#13;
                    &lt;/li&gt;&#13;
                &lt;/ol&gt;&#13;
&#13;
                &lt;h6 id="sec1"&gt;1. Processing headers&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;First thing first, let's install league/commonmark using Composer as usual.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;composer require league/commonmark&lt;/script&gt;&#13;
&#13;
                &lt;p&gt;In the first example, we need to parse file &lt;strong&gt;headers.md&lt;/strong&gt; which contains content as shown&#13;
                    below:&lt;/p&gt;&#13;
&#13;
                &lt;pre&gt;&#13;
# This is an H1&#13;
&#13;
## This is an H2&#13;
&#13;
###### This is an H6&lt;/pre&gt;&#13;
&#13;
                &lt;p&gt;We will first include the autoloader from Composer vendor folder. Then we will import &lt;strong&gt;CommonMarkConverter&lt;/strong&gt;&#13;
                    class and&#13;
                    instantiate an instance of it. At last, we use the method &lt;strong&gt;convertToHtml&lt;/strong&gt; to parse the&#13;
                    content of &lt;strong&gt;headers.md&lt;/strong&gt;.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
include 'vendor/autoload.php';&#13;
&#13;
use League\CommonMark\CommonMarkConverter;&#13;
&#13;
$converter = new CommonMarkConverter();&#13;
&#13;
echo $converter-&gt;convertToHtml(file_get_contents('headers.md'));&#13;
&#13;
&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;The outcome of running the script above is as shown below:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;h1&amp;gt;This is an H1&amp;lt;/h1&amp;gt;&#13;
&amp;lt;h2&amp;gt;This is an H2&amp;lt;/h2&amp;gt;&#13;
&amp;lt;h6&amp;gt;This is an H6&amp;lt;/h6&amp;gt;&#13;
&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec2"&gt;2. Processing lists&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;In this example, we need to parse file &lt;strong&gt;lists.md&lt;/strong&gt; which contains content as shown&#13;
                    below:&lt;/p&gt;&#13;
&#13;
                &lt;pre&gt;&#13;
* This is a&#13;
* This is b&#13;
* This is c&#13;
&#13;
+ This is A&#13;
+ This is B&#13;
+ This is C&lt;/pre&gt;&#13;
&#13;
                &lt;p&gt;Similar to the previous example, we use the same method &lt;strong&gt;convertToHtml&lt;/strong&gt; to do the job for&#13;
                    us.&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
include 'vendor/autoload.php';&#13;
&#13;
use League\CommonMark\CommonMarkConverter;&#13;
&#13;
$converter = new CommonMarkConverter();&#13;
&#13;
echo $converter-&gt;convertToHtml(file_get_contents('lists.md'));&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;The outcome of running the script above is as shown below:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;ul&amp;gt;&#13;
&amp;lt;li&amp;gt;This is a&amp;lt;/li&amp;gt;&#13;
&amp;lt;li&amp;gt;This is b&amp;lt;/li&amp;gt;&#13;
&amp;lt;li&amp;gt;This is c&amp;lt;/li&amp;gt;&#13;
&amp;lt;/ul&amp;gt;&#13;
&amp;lt;ul&amp;gt;&#13;
&amp;lt;li&amp;gt;This is A&amp;lt;/li&amp;gt;&#13;
&amp;lt;li&amp;gt;This is B&amp;lt;/li&amp;gt;&#13;
&amp;lt;li&amp;gt;This is C&amp;lt;/li&amp;gt;&#13;
&amp;lt;/ul&amp;gt;&#13;
&#13;
&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec3"&gt;3. Processing link&lt;/h6&gt;&#13;
                &lt;p&gt;In this example, we need to parse file &lt;strong&gt;link.md&lt;/strong&gt; which contains content as shown&#13;
                    below:&lt;/p&gt;&#13;
                &lt;pre&gt;[this is a link](www.google.com)&lt;/pre&gt;&#13;
&#13;
                &lt;p&gt;Similar to previous example, we use the same method &lt;strong&gt;convertToHtml&lt;/strong&gt; to do the job for&#13;
                    us.&lt;/p&gt;&#13;
&#13;
                &lt;p&gt;We will again use the same method:&lt;/p&gt;&#13;
&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
include 'vendor/autoload.php';&#13;
&#13;
use League\CommonMark\CommonMarkConverter;&#13;
&#13;
$converter = new CommonMarkConverter();&#13;
&#13;
echo $converter-&gt;convertToHtml(file_get_contents('link.md'));&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;The outcome of running the script above is as shown below:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;p&amp;gt;&amp;lt;a href=&amp;quot;www.google.com&amp;quot;&amp;gt;this is a link&amp;lt;/a&amp;gt;&amp;lt;/p&amp;gt;&#13;
                &lt;/script&gt;&#13;
&#13;
&#13;
                &lt;h6 id="sec4"&gt;4. Processing table&lt;/h6&gt;&#13;
                &lt;p&gt;In this example, we need to parse file &lt;strong&gt;table.md&lt;/strong&gt; which contains content as shown&#13;
                    below:&lt;/p&gt;&#13;
                &lt;pre&gt;&#13;
th | th(center) | th(right)&#13;
---|:----------:|----------:&#13;
td | td         | td&lt;/pre&gt;&#13;
&#13;
                &lt;p&gt;CommonMark is not able to parse table out of box, we need to install an extension to make that possible.&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: shell"&gt;&#13;
                    composer require webuni/commonmark-table-extension&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;We will create an environment, then add the table extension to the environment. Then create a converter using the environment.&#13;
                At last, we parse the markdown file as normal.&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
include 'vendor/autoload.php';&#13;
&#13;
use League\CommonMark\Converter;&#13;
use League\CommonMark\DocParser;&#13;
use League\CommonMark\Environment;&#13;
use League\CommonMark\HtmlRenderer;&#13;
use Webuni\CommonMark\TableExtension\TableExtension;&#13;
&#13;
$environment = Environment::createCommonMarkEnvironment();&#13;
&#13;
$environment-&gt;addExtension(new TableExtension());&#13;
&#13;
$converter = new Converter(new DocParser($environment), new HtmlRenderer($environment));&#13;
&#13;
echo $converter-&gt;convertToHtml(file_get_contents('table.md'));&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;p&gt;The outcome of running the script above is as shown below:&lt;/p&gt;&#13;
                &lt;script type="syntaxhighlighter" class="brush: php"&gt;&#13;
&amp;lt;table&amp;gt;&#13;
&amp;lt;thead&amp;gt;&#13;
&amp;lt;tr&amp;gt;&#13;
&amp;lt;th&amp;gt;th&amp;lt;/th&amp;gt;&#13;
&amp;lt;th align=&amp;quot;center&amp;quot;&amp;gt;th(center)&amp;lt;/th&amp;gt;&#13;
&amp;lt;th align=&amp;quot;right&amp;quot;&amp;gt;th(right)&amp;lt;/th&amp;gt;&#13;
&amp;lt;/tr&amp;gt;&#13;
&amp;lt;/thead&amp;gt;&#13;
&amp;lt;tbody&amp;gt;&#13;
&amp;lt;tr&amp;gt;&#13;
&amp;lt;td&amp;gt;td&amp;lt;/td&amp;gt;&#13;
&amp;lt;td align=&amp;quot;center&amp;quot;&amp;gt;td&amp;lt;/td&amp;gt;&#13;
&amp;lt;td align=&amp;quot;right&amp;quot;&amp;gt;td&amp;lt;/td&amp;gt;&#13;
&amp;lt;/tr&amp;gt;&#13;
&amp;lt;/tbody&amp;gt;&#13;
&amp;lt;/table&amp;gt;&#13;
                &lt;/script&gt;&#13;
&#13;
                &lt;h6 id="sec5"&gt;5. The end&lt;/h6&gt;&#13;
&#13;
                &lt;p&gt;&#13;
                    Hopefully this simple tutorial helped you with your development.&lt;br&gt;&#13;
                    If you like our post, please follow us on &lt;a href="http://twitter.com/startutorial" target="_blank"&gt;Twitter&lt;/a&gt;&#13;
                    and help spread the word. We need your support to continue.&#13;
                    &lt;br&gt;&#13;
                    If you have questions or find our mistakes in above tutorial, do leave a comment below to let us&#13;
                    know.&#13;
                &lt;/p&gt;</description><pubDate>Sun, 19 Feb 2017 23:56:58 +0000</pubDate></item></channel></rss>
