<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
<channel>
<title>Code In PHP</title>
<link>https://codeinphp.github.io</link>
<description>PHP and more...</description>
<language>en-us</language>
<item>
<title>Introducing PHPNews App</title>
<description><![CDATA[<p>Being able to keep oneself updated with latest trends, best practices and news is very crucial especially with the web evolving so rapidly today. This is equally important to become better or what they say modern developer as opposed to obsolete developer. As the technology stack evolves, the client requirements also evolve pushing us as developers to remain abreast of latest stuff as much as we possibly can.</p>
<p>Two of the most common methods to stay up-to-date with latest stuff is to use some RSS/Atom Aggregator or subscription via emails at various sites. These work fine but I was personally overwhelmed by the amount of new updates and posts I used to get, it was kind of hard to keep the track of it all with that many subscriptions from various sources on different technologies. I <em>could</em>  have minimized the subscriptions but that wouldn't save the actual purpose.</p>
<p>Therefore being a developer, often times, you come up with your own solution which fits your needs. I wanted just a simple and focused app on just one technology eg PHP that would give me updates from various sources in one central place without bloating me away with too many or stale posts. Since idea was simple, I didn't want to spend too much time on Android so I took the route of using JavaScript to create this app. It turned out there are quite some ways to create <strong>Native</strong> apps today using one technology that can run across devices and platforms. I found <a href="https://www.nativescript.org/">NativeScript</a> quick and easy to get started with although there are other solutions too to make native apps such as ReactNative, Xamarin, Flutter, etc.</p>
<p>Over the weekend, I went on to creating this app called <strong>PHPNews</strong> and I believe end result is exactly what I wanted as it serves the purpose, here is screenshot: </p>
<p><img src="https://codeinphp.github.io/images/15467873715c321a2b3c5f2.jpg" alt="PHPNews Screen" /></p>
<p>It collects information from various sources including official blogs of PHP frameworks such as Laravel, Symfony, Zend Framework and CMSs like WordPress and last but not the least our old friend planet-php.net.</p>
<p>Definitely give it a try and also share any suggestions or improvements.</p>
<p><strong><a href="https://play.google.com/store/apps/details?id=io.codeinphp.phpnews">View PHPNews on Android PlayStore</a></strong></p>]]></description>
<link>https://codeinphp.github.io/post/introducing-phpnews-app</link>
<pubDate>Sun, 06 Jan 2019 20:27:00 +0500</pubDate>
</item>
<item>
<title>Laravel: Automatic Vendor Cleanup Command</title>
<description><![CDATA[<p>When installing composer packages, they come up with <strong>lot of useless files and folders</strong> such as <code>.git</code>, <code>tests</code>, <code>readme.md</code> and more. When project becomes bigger with many packages, this junk takes considerable disk space. Since I work with Laravel framework most of the time, I created a command that allows me to automatically delete all these junk files whenever I happen to install or update composer packages.</p>
<p>Here is the pattern used by <code>glob</code> function to detect and delete all junk files:</p>
<pre><code>protected $patterns = [
    '.git',
    '.github',
    'test',
    'tests',
    'travis',
    'demo',
    'demos',
    'license',
    'changelog*',
    'contributing*',
    'upgrading*',
    'upgrade*',
    '.idea',
    '.vagrant',
    'readme*',
    '_ide_helper.php',
    '{,.}*.yml',
    '*.yaml',
    '*.md',
    '*.xml',
    '*.log',
    '*.txt',
    '*.dist',
    '*.pdf',
    '*.xls',
    '*.doc',
    '*.docx',
    '*.png',
    '*.gif',
    '*.jpg',
    '*.bmp',
    '*.jpeg',
    '*.ico',
    '.php_cs*',
    '.scrutinizer',
    '.gitignore',
    '.gitattributes',
    '.editorconfig',
    'dockerfile',
    'composer.json',
    'composer.lock',
];</code></pre>
<p>The command itself can be <a href="https://github.com/sarfraznawaz2005/laravel55-starter/blob/master/Modules/Core/Console/VendorCleanup.php">seen here</a>.</p>
<p>To automatically cleanup junk files/folders when installing or updating composer packages in Laravel, <code>@php artisan vendor:cleanup</code> should be added under the <code>post-autoload-dump</code> section in <code>composer.json</code> file. Or we can also trigger it manually anytime by typing <code>php artisan vendor:cleanup --o</code> where <code>--o</code> is optional argument to display verbose output.</p>
<p>If you actually want to be able to use this idea of cleanup of useless files in any PHP project (Laravel or not), you might want to create a <a href="https://getcomposer.org/doc/articles/plugins.md">composer plugin</a> instead and install it globally that can then work across PHP projects and cleanup useless files from the <code>vendor</code> folder.</p>
<p>If you witness any issue or something missing in the pattern list shown above, please leave your suggestion/improvements in comments. Thanks</p>]]></description>
<link>https://codeinphp.github.io/post/laravel-automatic-vendor-cleanup-command</link>
<pubDate>Thu, 25 Jan 2018 00:16:00 +0500</pubDate>
</item>
<item>
<title>Whatsapp Chat from CLI Using Puppeteer</title>
<description><![CDATA[<p><a href="https://github.com/GoogleChrome/puppeteer">GoogleChrome puppeteer</a>  is interesting project to create browser automation tools, testing tools or web scrapping. I was wondering to use it for something useful and an idea popped in about creating CLI application that can be used to send and receive messages on Whatsapp. So I went on to creating <strong><a href="https://github.com/sarfraznawaz2005/whatspup">Whatspup</a></strong>, a name based on both Whatsapp and puppeteer.</p>
<h2>Features</h2>
<ul>
<li>Send and receive messages</li>
<li>Read Receipts</li>
<li>Switch between users to chat with</li>
<li>Popup notifications for new chat messages</li>
<li>Privacy settings for popup notifications</li>
<li>One-time authentication, no need to scan QR code again and again</li>
<li>Windowless/headless (hidden) mode</li>
<li>Colorful chat messages</li>
</ul>
<h2>Screenshot</h2>
<p><img src="https://raw.githubusercontent.com/sarfraznawaz2005/whatspup/master/screenshot.jpg" alt="Main Window" /></p>
<hr />
<p><strong><a href="https://github.com/sarfraznawaz2005/whatspup">Head over to Whatspup repository and start using it :)</a></strong></p>]]></description>
<link>https://codeinphp.github.io/post/whatsapp-chat-from-cli-using-puppeteer</link>
<pubDate>Sun, 10 Dec 2017 16:06:00 +0500</pubDate>
</item>
<item>
<title>Laravel QueryDumper</title>
<description><![CDATA[<p>I wanted simple and quick way to see all running queries on any page of my laravel application especially accompanied by MySQL's <code>EXPLAIN</code> results. So I created very simple package called <strong>Laravel QueryDumper</strong> that allows me see just that.</p>
<h1>Screenshot</h1>
<p><img src="https://camo.githubusercontent.com/35a43c98152c978c9df07b32f833609fe065edac/68747470733a2f2f7261772e6769746875622e636f6d2f7361726672617a6e6177617a323030352f717565727964756d7065722f6d61737465722f73637265656e2e706e67" alt="enter image description here" /></p>
<hr />
<p><strong><a href="https://github.com/sarfraznawaz2005/querydumper">Checkout Laravel QueryDumper</a></strong></p>]]></description>
<link>https://codeinphp.github.io/post/laravel-querydumper</link>
<pubDate>Sat, 16 Sep 2017 18:16:00 +0500</pubDate>
</item>
<item>
<title>Introducing Floyer</title>
<description><![CDATA[<p>At my company, they still use ^svn^ and on top of that ^ftp^ and it was pain in the ass to upload files especially when client didn't have dedicated hosting or where there was no SSH access available. I did find some git-to-ftp or svn-to-ftp deployment tools but they were very slow because they uploaded each file individually.</p>
<p>I sat down over the weekend and came up with my own solution <strong><a href="https://github.com/sarfraznawaz2005/floyer">Floyer</a></strong> (shortened from FTPDeployer). It works with both <code>git</code> and <code>svn</code> and is quit fast able to upload hundreds of files in few seconds. Other than FTP, it also supports SFTP.</p>
<h1>How does it work</h1>
<ul>
<li>It stores revision/commit hash on the server in a file when deployment is started.</li>
<li>On next deployment, it compares local revision with remote one thereby able to deploy only the files changed between these two revisions.</li>
<li>Once it knows what files to upload, it creates zip archive of these files to be deployed on the server.</li>
<li>Rather than uploading each file individually (which is very slow process), it creates and uploads zip archive file to server where there is corresponding extract zip PHP script which extracts these files very fast. This script is also created and uploaded by Floyer.</li>
<li>After deployment is finished, zip archive and extract script is deleted automatically.</li>
</ul>
<p>Deploying by uploading and extracting archive file not only makes deployment fast but also we don't have to worry about some permission issues or creating new directories and so on because extract script runs from server itself thereby avoiding these issues.</p>
<h1>Screenshot</h1>
<p><img src="https://camo.githubusercontent.com/dbd0d6326b7820922db866f0095af8752ff6e3bf/68747470733a2f2f7261772e6769746875622e636f6d2f7361726672617a6e6177617a323030352f666c6f7965722f6d61737465722f73637265656e73686f742e706e67" alt="enter image description here" /></p>
<p><strong><a href="https://github.com/sarfraznawaz2005/floyer">Checkout Floyer at Github</a></strong></p>]]></description>
<link>https://codeinphp.github.io/post/introducing-floyer</link>
<pubDate>Thu, 24 Aug 2017 22:03:00 +0500</pubDate>
</item>
<item>
<title>Sockets with PHP and Node</title>
<description><![CDATA[<p>I was looking to implement real time notifications system via sockets without having to use any third party services such as <a href="https://pusher.com/">Pusher</a>, etc. I just wanted to be able to send notifications from PHP side to the client and instantly show them on the web application similar to Facebook notifications. </p>
<p>First I came across <a href="http://socketo.me/">ratchet</a> library, it worked great but problem emerged when setting it up on secure connection (https) on my host (siteground), tried apache proxy module and everything else told on the internet but to no avail (it seems siteground has problem with ratchet on https) so in the end I had to drop ratchet.</p>
<p>Then I thought of using <a href="https://socket.io/">socket.io</a> with Node+PHP and with my research I came across <a href="https://github.com/Wisembly/elephant.io">elephant.io</a> library (though it isn't updated recently) and this one worked wonderfully well both on non-secure and secure protocols allowing us to send and receive messages from PHP with node-based server.</p>
<p>Here are the steps that I followed to get my notification system working.</p>
<p><strong>Install elephant.io</strong></p>
<p>For your PHP application, install <code>elephant.io</code> via composer:</p>
<pre><code>composer require wisembly/elephant.io</code></pre>
<p><strong>Install Node Dependencies</strong></p>
<p>Create a directory in your project root and under it create a file named <code>package.json</code> with these contents:</p>
<pre><code>{
    "name": "elephantIO_example_emitter",
    "version": "3.0.0",
    "main": "server.js",

    "scripts": {
        "start": "supervisor --debug server.js"
    },

    "dependencies": {
        "socket.io": "~1",
        "winston": "*"
    }
}</code></pre>
<p>On newly created directory run command <code>npm install --save</code>. This will install <code>socket.io</code> and logger library.</p>
<p>In same newly created directory, create a file <code>server.js</code> with these contents:</p>
<pre><code>var server     = require('http').createServer(),
    io         = require('socket.io')(server),
    logger     = require('winston'),
    port       = 1337;

// Logger config
logger.remove(logger.transports.Console);
logger.add(logger.transports.Console, { colorize: true, timestamp: true });
logger.info('SocketIO &gt; listening on port ' + port);

io.on('connection', function (socket){
    var nb = 0;

    logger.info('SocketIO &gt; Connected socket ' + socket.id);

    socket.on('broadcast', function (message) {
        ++nb;
        logger.info('ElephantIO broadcast &gt; ' + JSON.stringify(message));

        // send to all connected clients
        io.sockets.emit("broadcast", message);
    });

    socket.on('disconnect', function () {
        logger.info('SocketIO : Received ' + nb + ' messages');
        logger.info('SocketIO &gt; Disconnected socket ' + socket.id);
    });
});

server.listen(port);</code></pre>
<p>Run <code>server.js</code> file through node by typing <code>node server.js</code>, you should see message that server has started on specified port.</p>
<p><strong>Client Side</strong></p>
<p>Put following javascript code in your application's page/footer:</p>
<pre><code>&lt;script src='//cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.4/socket.io.min.js'&gt;&lt;/script&gt;

&lt;script&gt;
var socket = io.connect('//127.0.0.1:1337');

socket.on('connect', function () {
    console.log('connected');

    socket.on('broadcast', function (data) {
        //console.log(data);
        //socket.emit("broadcast", data);
        alert(data.text);
    });

    socket.on('disconnect', function () {
        console.log('disconnected');
    });
});
&lt;/script&gt;</code></pre>
<p><strong>Sending Notification from PHP</strong></p>
<p>Here is how you can send a message to all connected clients:</p>
<pre><code>require __DIR__ . '/vendor/autoload.php';

use ElephantIO\Client;
use ElephantIO\Engine\SocketIO\Version1X;

$client = new Client(new Version1X('//127.0.0.1:1337'));

$client-&gt;initialize();
// send message to connected clients
$client-&gt;emit('broadcast', ['type' =&gt; 'notification', 'text' =&gt; 'Hello There!']);
$client-&gt;close();</code></pre>
<p>and that's all there is to it.</p>
<p><strong>Installing and Running Node on Production Site</strong></p>
<p>I was on <code>CentOSv6</code> and I installed node by following <a href="https://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-managed-hosting-accounts">this guide</a>. Then I created simple php file that will be run by cron so that node server is automatically started/restarted if it is not running:</p>
<pre><code>$nodePath = 'your node binary path here';
$filePath = 'your server.js file path';
shell_exec($nodePath . ' ' . $filePath);</code></pre>
<p>and then specify that file in cron to run at your specified time intervals.</p>
<p><strong>Important Notes</strong></p>
<ul>
<li>I was having bit of issue getting node path from PHP script where I initially installed it so I copied the nodejs folder to my <code>public_html</code> folder (app's root).</li>
<li>On production site, I had to type actual server IP rather than <code>127.0.0.1</code> on client side code eg instead of <code>var socket = io.connect('//127.0.0.1:1337');</code>, it has to be <code>var socket = io.connect('//SERVER_IP_HERE:1337');</code></li>
<li>If you are having issue getting it to work on https, check out <a href="https://github.com/Wisembly/elephant.io/issues?utf8=%E2%9C%93&amp;q=">issues section</a> to fix it.</li>
<li>Check out <strong>examples</strong> folder of <code>elephant.io</code> to know how to send or receive messages both from PHP as well as Javascript.</li>
</ul>]]></description>
<link>https://codeinphp.github.io/post/sockets-with-php-and-node</link>
<pubDate>Sat, 22 Jul 2017 02:19:00 +0500</pubDate>
</item>
<item>
<title>Laravel VisitLog</title>
<description><![CDATA[<p>VisitLog is a simple Laravel 5 package that can be used to log visitor information and save it into database. </p>
<h2>Features</h2>
<ul>
<li>Other than basic log such as IP, Browser and OS, it can also log Location information.</li>
<li>Allows to log both unique and non-unique visits based on IP.</li>
<li>Allows to cache the visits based on IP.</li>
<li>Allows to log authenticated user info.</li>
<li>Provides log viewer page out of box.</li>
</ul>
<h2>Screenshots</h2>
<p><img src="https://raw.github.com/sarfraznawaz2005/visitlog/master/screen.png" alt="Main Window" /></p>
<hr />
<p><a href="https://github.com/sarfraznawaz2005/visitlog">Visit Package Repository</a> to know more about it and installation.</p>]]></description>
<link>https://codeinphp.github.io/post/laravel-visitlog</link>
<pubDate>Tue, 13 Sep 2016 17:50:00 +0500</pubDate>
</item>
<item>
<title>From Bad to Good: DI, DIC and Services</title>
<description><![CDATA[<p>In this post, I intend to touch the concepts of:</p>
<ul>
<li>Dependency Injection (<a href="http://codeinphp.github.io/post/dependency-injection-in-php/">My previous post on DI</a>)</li>
<li>Dependency Injection Container (DIC)</li>
<li>Services</li>
</ul>
<p>Even though these terms seems scary at first especially to new-comers but are really easy to understand and help write <strong>quality code that is easy to understand and extend</strong>. We will take a ^legacy code^ and convert it into object-oriented one by using these principles.</p>
<p>Suppose we have simple application that sends newsletter email to all its subscribers, here is the legacy code:</p>
<pre><code>// file: index.php or could also be considered as Controller file in MVC paradigm

require __DIR__ . 'vendor/autoload.php';

use Demo\Mailer\SmtpMailer;

$dsn = 'sqlite:' . __DIR__ . 'database.sqlite';
$pdo = new PDO($dsn);

$mailer = new SmtpMailer('smtp.example.com', 'user', 'password', '465');

$sql = 'SELECT * from subscribers';

foreach ($pdo-&gt;query($sql) as $row) {
    $mailer-&gt;sendMessage(
        $row['email'],
        'This is the email body',
        $row['name'],
        'info@example.com'
    );
}</code></pre>
<p>Right now above code smells and has these problems:</p>
<ul>
<li>Logic is mixed up, SQL queries, sending emails database configuration is all in one file</li>
</ul>
<p>To fix this, first instinct is to convert it into class:</p>
<pre><code>class SubscriberMailer
{
    public function sendEmails()
    {
        $dsn = 'sqlite:' . __DIR__ . 'database.sqlite';
        $pdo = new PDO($dsn);

        $mailer = new SmtpMailer('smtp.example.com', 'user', 'password', '465');

        $sql = 'SELECT * from subscribers';

        foreach ($pdo-&gt;query($sql) as $row) {
            $mailer-&gt;sendMessage(
                $row['email'],
                'This is the email body',
                $row['name'],
                'info@example.com'
            );
        }
    }
}</code></pre>
<p>This looks good to eye but it has more problems:</p>
<ul>
<li>Logic is <em>still</em> mixed up, SQL queries, sending emails database configuration is all in one file</li>
<li>It has hard-coded dependencies (tight-coupling) on PDO and Mailer class, what if we wanted to change Mailer class ?</li>
<li>It is hard to unit-test because of tight coupling</li>
</ul>
<p>Let's try to fix these problems. We can see that this class has dependency on PDO so instead of hard-coding it inside <code>SubscriberMailer</code> class, we can ^pass^ it via its constructor which now makes the class:</p>
<pre><code>class SubscriberMailer
{
    protected $pdo = null;

    public function __construct($pdo)
    {
        $this-&gt;pdo = $pdo;
    }

    public function sendEmails()
    {
        $mailer = new SmtpMailer('smtp.example.com', 'user', 'password', '465');

        $sql = 'SELECT * from subscribers';

        foreach ($this-&gt;pdo-&gt;query($sql) as $row) {
            $mailer-&gt;sendMessage(
                $row['email'],
                'This is the email body',
                $row['name'],
                'info@example.com'
            );
        }
    }
}</code></pre>
<p>This is a bit better, the class doesn't care where PDO objects comes from, it just needs one to operate and you can't instantiate the class without providing one so it makes its intention clear. So this is what is called <strong>Dependency Injection</strong>, no need to fear even though the term sounded scary initially (read my <a href="http://codeinphp.github.io/post/dependency-injection-in-php/">previous article</a> on more ways of injecting dependencies). Here is how we use above class at this point of the time:</p>
<pre><code>require __DIR__ . 'vendor/autoload.php';

use Demo\Mailer\SmtpMailer;
use Demo\Mailer\SubscriberMailer;

$dsn = 'sqlite:' . __DIR__ . 'database.sqlite';
$pdo = new PDO($dsn);

$subscriberMailer = new SubscriberMailer($pdo);
$subscriberMailer-&gt;sendEmails();</code></pre>
<p>This is starting to look better compared to first snippet of code. However, we still have a problem in that we have hard-coded smtp config into our class, what if we wanted to change the smtp config without touching the class ? Or what if we had different setup of smtp config for development and production ? Remember a class should be a black-box which simply does its job without editing it again and again, you can only extend it not edit it. So this reasoning hints us that like pdo, we should also pass smtp config via class's constructor and move it from the class itself.</p>
<pre><code>class SubscriberMailer
{
    protected $pdo = null;
    protected $smtpConfig = [];

    public function __construct($pdo, array $smtpConfig)
    {
        $this-&gt;pdo = $pdo;
        $this-&gt;smtpConfig = $smtpConfig;
    }

    public function sendEmails()
    {
        $mailer = new SmtpMailer(
            $this-&gt;smtpConfig['host'],
            $this-&gt;smtpConfig['user'],
            $this-&gt;smtpConfig['password'],
            $this-&gt;smtpConfig['port']
        );

        $sql = 'SELECT * from subscribers';

        foreach ($this-&gt;pdo-&gt;query($sql) as $row) {
            $mailer-&gt;sendMessage(
                $row['email'],
                'This is the email body',
                $row['name'],
                'info@example.com'
            );
        }
    }
}</code></pre>
<p>Usage:</p>
<pre><code>require __DIR__ . 'vendor/autoload.php';

use Demo\Mailer\SmtpMailer;
use Demo\Mailer\SubscriberMailer;

$dsn = 'sqlite:' . __DIR__ . 'database.sqlite';
$pdo = new PDO($dsn);

$subscriberMailer = new SubscriberMailer($pdo, [
   'host' =&gt; 'smtp.example.com',
   'user' =&gt; 'user',
   'password' =&gt; 'password',
   'port' =&gt; '465',
]);

$subscriberMailer-&gt;sendEmails();</code></pre>
<p>This is better, we can now readily change smtp config in one place and we don't have to touch our class. It still has these problems though:</p>
<ul>
<li>It is tightly coupled to SMTP mailer, what if we wanted to change mailer from smtp to another one like sendmail ?</li>
<li>SQL is still written in our class, logic is mixed up, our mail class shouldn't know about users or interact with database, it just needs to send emails !</li>
</ul>
<blockquote>
<p><code>Hint</code>: The <code>new</code> keyword is considered code-smell, whenever you
encounter it, it means it is something you should pass via dependency
injection.</p>
</blockquote>
<p>So by now we know that to remove hard-coded dependency or tight-coupling, we should pass it instead via dependency injection. So instead of passing mailer config, we should pass mailer object:</p>
<pre><code>class SubscriberMailer
{
    protected $pdo = null;
    protected $mailer = null;

    public function __construct(\PDO $pdo, SmtpMailer $mailer)
    {
        $this-&gt;pdo = $pdo;
        $this-&gt;mailer = $mailer;
    }

    public function sendEmails()
    {
        $sql = 'SELECT * from subscribers';

        foreach ($this-&gt;pdo-&gt;query($sql) as $row) {
            $this-&gt;mailer-&gt;sendMessage(
                $row['email'],
                'This is the email body',
                $row['name'],
                'info@example.com'
            );
        }
    }
}</code></pre>
<p>Usage:</p>
<pre><code>require __DIR__ . 'vendor/autoload.php';

use Demo\Mailer\SmtpMailer;
use Demo\Mailer\SubscriberMailer;

$dsn = 'sqlite:' . __DIR__ . 'database.sqlite';
$pdo = new PDO($dsn);

$mailer = new SmtpMailer('smtp.example.com', 'user', 'password', '465');

$subscriberMailer = new SubscriberMailer($pdo, $mailer);       
$subscriberMailer-&gt;sendEmails();</code></pre>
<p>This is better, we removed hard-coded dependency to smtp mailer and notice that we have also type-hinted the <code>PDO</code> and <code>SmtpMailer</code> in the constructor of our class, this is extremely helpful because:</p>
<ul>
<li>Our class makes clear intention that it needs a <code>PDO</code> and <code>SmtpMailer</code> to work properly</li>
<li>If somebody passes something other than these two dependencies, they would get clear error message</li>
<li>Type-hinting makes our code self-documenting</li>
<li>It makes IDE auto-completion </li>
</ul>
<p>Right now our mailer class knows it needs an instance of <code>SmtpMailer</code> to work and it should have a <code>sendMessage</code> method. Remember, we refactored our code in hope that we might use some other type of mailer like sendmail but problem is that it might not necessarily have the <code>sendMessage</code> method which means we cannot use it. So how do we solve this problem to be able to use some other type of mailer implementation ? Well the answer is to use an interface/contract and use that instead:</p>
<pre><code>// app/Demo/Contracts/MailerInterface.php
interface MailerInterface
{
   public function sendMessage($email, $body, $subject, $from);
}

// app/Demo/Mailer/SmtpMailer.php
use Demo\Contracts\MailerInterface;

class SmtpMailer implements MailerInterface
{
    public function sendMessage($email, $body, $subject, $from) {
        // code to send email
    }
}

// app/Demo/Mailer/SubscriberMailer.php    
class SubscriberMailer
{
    protected $pdo = null;
    protected $mailer = null;

    public function __construct(\PDO $pdo, MailerInterface $mailer)
    {
        $this-&gt;pdo = $pdo;
        $this-&gt;mailer = $mailer;
    }

    public function sendEmails()
    {
        $sql = 'SELECT * from subscribers';

        foreach ($this-&gt;pdo-&gt;query($sql) as $row) {
            $this-&gt;mailer-&gt;sendMessage(
                $row['email'],
                'This is the email body',
                $row['name'],
                'info@example.com'
            );
        }
    }
}</code></pre>
<p>Just like every step that we are performing, this step also has nice advantages:</p>
<ul>
<li>Our <code>SubscriberMailer</code> class is now greatly expandable since it now accepts <strong>ANY object</strong> that implements <code>MailerInterface</code> that has <code>sendMessage</code> method</li>
<li>It documents our code a bit more, it is clear now how an object should be constructed that implements the <code>MailerInterface</code></li>
</ul>
<p>All well and good so far. We now see that in our class has SQL to get users. Again it should not care about talking to database, it just needs users' emails to send emails to. To fix this, we need use the <strong><a href="http://shawnmc.cool/the-repository-pattern">Repository Pattern</a></strong> which is essentially a class talking to database to manipulate specific entity, in this case users. So we can pass <code>UserRepository</code> as dependency that has a method to get all users:</p>
<pre><code>// app/Demo/Mailer/SubscriberMailer.php
use Demo\Contracts\MailerInterface;
use Demo\Repositories\UserRepository;

class SubscriberMailer
{
    protected $mailer = null;
    protected $userRepository = null;

    public function __construct(MailerInterface $mailer, UserRepository $userRepository)
    {
        $this-&gt;mailer = $mailer;
        $this-&gt;userRepository = $userRepository;
    }

    public function sendEmails()
    {
        $users = $this-&gt;userRepository-&gt;getAll();

        foreach ($users as $user) {
            $this-&gt;mailer-&gt;sendMessage(
                $user-&gt;email,
                'This is the email body',
                $user-&gt;name,
                'info@example.com'
            );
        }
    }
}</code></pre>
<p>Usage:</p>
<pre><code>require __DIR__ . 'vendor/autoload.php';

use Demo\Mailer\SmtpMailer;
use Demo\Mailer\SubscriberMailer;
use Demo\Repositories\UserRepository;

$mailer = new SmtpMailer('smtp.example.com', 'user', 'password', '465');

$subscriberMailer = new SubscriberMailer($mailer, new UserRepository);    
$subscriberMailer-&gt;sendEmails();</code></pre>
<p>Awesome! our <code>SubscriberMailer</code> class now does not have any mixed-up logic, it is complete black-box whose task is to send emails to provided users. It doesn't need to care about how you pass <code>MailerInterface</code> or <code>UserRepository</code>, it just needs them to operate. It has only one task of sending emails. Not to mention that our class is also easy to be unit-tested. Notice also that we removed PDO as dependency since it is now job of <code>UserRepository</code> to give us the users.</p>
<p>We can now call our class a <strong>Service</strong> that performs one and only one task without any coupling. If you have heard about <strong><a href="https://en.wikipedia.org/wiki/Service-oriented_architecture">Service-Oriented Architecture</a></strong>, this is what it is, a collection of service classes with one and only one responsibility each without any hard-coded dependencies.</p>
<p>At this point of the time, we are all good with our class but one of the downsides of Dependency Injection is that all the complexity of creating and configuring objects is your job. Now this isn't that bad since it happens at one place and gives you the control but it is something which we can still improve.</p>
<p>To do this, we need to leverage what is called <strong>Dependency Injection Container</strong> (DIC). The job of DIC is to create and configure objects for us. There are many DIC out there for PHP but let's see our modified code using famous <strong><a href="http://pimple.sensiolabs.org/">Pimple</a></strong> container, here we wrap the dependencies or services into Pimple container. I am not going into details of how to use it, you should refer to its documentation.</p>
<pre><code>// file: container.php

use Demo\Mailer\SmtpMailer;
use Demo\Repositories\UserRepository;
use Pimple\Container;
use Demo\Mailer\SubscriberMailer;

$container = new Pimple();

// container can also hold configs - ideally should be put in separate file...
$container['smtp_config'] = [
   'host' =&gt; 'smtp.example.com',
   'user' =&gt; 'user',
   'pass' =&gt; 'password',
   'port' =&gt; '465',
];

$container['mailer'] = $container-&gt;share(function(Pimple $container){
   return new SmtpMailer(
      $container['smtp_config']['host'],
      $container['smtp_config']['user'],
      $container['smtp_config']['pass'],
      $container['smtp_config']['port']
   );
});

$container['userRepository'] = $container-&gt;share(function(){
   return new UserRepository();
});

$container['subscriberMailer'] = $container-&gt;share(function(Pimple $container){
   return new SubscriberMailer($container['mailer'], $container['userRepository']);
});

// file: index.php

require __DIR__ . 'vendor/autoload.php';
require __DIR__ . 'container.php';

$subscriberMailer = $container['subscriberMailer'];
$subscriberMailer-&gt;sendEmails();</code></pre>
<p>Notice how clear and concise our <code>index.php</code> code is now compared to initial version. </p>
<p>Using the DIC provides us with these advantages:</p>
<ul>
<li>Wrapping our object creation in container's anonymous function makes object creation lazy which means object isn't created <em>only until needed</em> and if we never reference our <code>SubscriberMailer</code> class, those objects are never created at all saving us memory !</li>
<li>Using the container's <code>share</code> method means no matter how many times we need, it will always give us same original object instance. If we need to send many emails, we don't need many instances. This also makes code a bit more faster.</li>
<li>All the logic of which objects depend on other objects is abstracted away into container itself, we don't need to worry how they are created or what their dependencies are, we just use our services straight away out of container.</li>
<li>If we ever need to change config or something, we only edit it at one place, nobody needs to know about this change.</li>
</ul>
<hr />
<p>In conclusion, no matter which framework you use, these principles can be applied to make code which is easy to understand, extend and test.</p>]]></description>
<link>https://codeinphp.github.io/post/from-bad-to-good-di-dic-and-services</link>
<pubDate>Sun, 28 Aug 2016 14:37:00 +0500</pubDate>
</item>
<item>
<title>Fast MySQL Backup and Restore</title>
<description><![CDATA[<p>Backing up and restoring MySQL database is generally trivial task however when database is huge, it is really a pain to do so because of amount of time it takes to perform backup/restore operation with conventional tools like PHPMyAdmin or similar.</p>
<p>If you have <strong>SSH access</strong> to server, we can leverage built-in MySQL commands <a href="https://dev.mysql.com/doc/refman/5.5/en/mysqldump.html"><code>mysqldump</code></a> and <a href="http://dev.mysql.com/doc/refman/5.7/en/mysql.html"><code>mysql</code></a> respectively to backup and restore big database really fast.</p>
<p><strong>To Backup Database:</strong></p>
<p><code>mysqldump -uDB_USER_HERE -pDB_PASSWORD_HERE DATABASE_NAME_HERE &gt; backup.sql</code></p>
<p><strong>To Restore Database:</strong></p>
<p><code>mysql -uDB_USER_HERE -pDB_PASSWORD_HERE DATABASE_NAME_HERE &lt; backup.sql</code></p>
<hr />
<p><strong>Note:</strong> If you don't have SSH access, you can use tools like <a href="http://www.mysqldumper.net/">MySQLDumper</a> which does fairly good job but not as fast as <code>mysqldump</code> and <code>mysql</code> commands of course.</p>]]></description>
<link>https://codeinphp.github.io/post/fast-mysql-backup-and-restore</link>
<pubDate>Sun, 29 May 2016 18:57:00 +0500</pubDate>
</item>
<item>
<title>Coding to Interface</title>
<description><![CDATA[<p>One of the nicest things you can add to your programming skills is <strong>coding to interface</strong>. One of the <a href="https://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29">five principles of S.O.L.I.D</a> is <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency inversion principle</a> which states:</p>
<blockquote>
<p>In object-oriented programming, the dependency inversion principle
refers to a specific form of decoupling software modules. When
following this principle, the conventional dependency relationships
established from high-level, policy-setting modules to low-level,
dependency modules are reversed, thus rendering high-level modules
independent of the low-level module implementation details. The
principle states:<a href="https://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29">1</a></p>
<p>A. High-level modules should not depend on low-level modules. Both
should depend on abstractions.</p>
<p>B. Abstractions should not depend on details. Details should depend on
abstractions.</p>
</blockquote>
<p>Pretty <em>formal</em> definition hun ? let's understand through example actually.</p>
<p>Imagine we have rudimentary MySQL wrapper class:</p>
<pre><code>class Mysql
{
    protected $db = null;

    public function connect($dsn, $user = '', $pass = '')
    {
        $this-&gt;db = new PDO($dsn, $user, $pass);
    }

    public function query($query)
    {
        return $this-&gt;db-&gt;query($query);
    }
}</code></pre>
<p>Pretty common and valid code in old days we used to be proud while writing such class. There are couple of problems associated with it though:</p>
<ul>
<li>The class <code>Mysql</code> has implicit dependency (tight-coupling) on the <code>PDO</code> class. All dependencies should always be explicit not implicit.</li>
<li>It is hard to unit-test due to implicit dependency</li>
</ul>
<p>Let's use above class:</p>
<pre><code>class User
{
    private $database = null;

    public function __construct()
    {
        $this-&gt;database = new Mysql();
        $this-&gt;database-&gt;connect('mysql:host=localhost;dbname=test', 'root', '');
    }

    public function getUsers()
    {
        $users = $this-&gt;database-&gt;query('SELECT * FROM users ORDER BY id DESC');
        print_r($users);
    }
}

$user = new User();
$user-&gt;getUsers();</code></pre>
<p>Again pretty common piece of code but again this one has even more problems:</p>
<ul>
<li>The class <code>User</code> has implicit dependency (tight-coupling) on the <code>Mysql</code> class. All dependencies should always be explicit not implicit.</li>
<li>It is hard to unit-test due to implicit dependency</li>
<li>If we wanted to change database credentials, we need to edit the <code>User</code> class which is not good; every class should be completely <strong>modular</strong> or black box. If we need to operate further on it, we should actually use its public properties and methods instead of editing it again and again.</li>
<li>Let's assume right now class is using MySQL as database. What if we wanted to use some other type of database ? You will have to modify class.</li>
<li>The <code>User</code> class does not necessarily need to know about database connection, it should be confined to its own functionality only. So writing database connection code in <code>User</code> class doesn't make it modular. This defeats the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single responsibility principle</a>.</li>
</ul>
<p>You might wonder above code has problems but these days we write code based on MVC design pattern and follow best practices and write <em>modern code</em> but I am sure below code is pretty common even today using any framework you use:</p>
<pre><code>class UserController extends Controller
{
    public function actionListAllUsers()
    {          
       // fetch all users from database
        $users = User::model()-&gt;findAll();

       // show them on screen
        print_r($users);          
    }
}</code></pre>
<p>If you analyze this has same problems again in that class <code>UserController</code> is tightly coupled (implicit dependency) with <code>User</code> model class which also makes it hard to unit-test.</p>
<p>This means:</p>
<blockquote>
<p>Coupled Code is Evil BIG DOT</p>
</blockquote>
<h2>So what's the solution ?</h2>
<p>The solution is <a href="https://en.wikipedia.org/wiki/Dependency_injection">Dependency Injection</a> (see my previous post <a href="http://codeinphp.github.io/post/dependency-injection-in-php/">Dependency Injection in PHP</a>). The idea behind Dependency Injection is that instead of writing implicit dependencies, we should pass/provide those via constructor or setter method or even interface.</p>
<p>Let's refactor <code>User</code> class code and pass our dependency via constructor instead of hard-coding it inside <code>User</code> class method:</p>
<pre><code>class User
{
    private $database = null;

    public function __construct(Mysql $database)
    {
        $this-&gt;database = $database;
    }

    public function getUsers()
    {
        $users = $this-&gt;database-&gt;query('SELECT * FROM users ORDER BY id DESC');
        print_r($users);
    }
}

$database = new Mysql();
$database-&gt;connect('mysql:host=localhost;dbname=test', 'root', '');
$user = new User($database);
$user-&gt;getUsers();</code></pre>
<p>This is much better! We no more have implicit dependency on <code>Mysql</code> class which also makes our <code>User</code> class easier to unit-test. The class makes clear intention that it needs some sort of <code>Mysql</code> class. It also doesn't know (or care) where <code>Mysql</code> will come form, it just needs one to operate. The <code>User</code> class is now completely modular and follows single responsibility principle (that of manipulating users).</p>
<p>In the similar way, we can also improve our modern code:</p>
<pre><code>class UserController extends Controller
{
    protected $user;

    public function __construct(User $user)
    {
        $this-&gt;user = $user;
    }

    public function actionListAllUsers()
    {          
       // fetch all users from database
        $users = $this-&gt;user-&gt;findAll();

       // show them on screen
        print_r($users);          
    }
}</code></pre>
<p>Here again we pass dependency (<code>User</code> class) of <code>UserController</code> via its constructor making it much better. So all good ? Not really...</p>
<h2>We still have a problem</h2>
<p>One problem with <code>User</code> class which still persists is that it is tied to <strong>specific type of database</strong> (<code>Mysql</code>). What if we wanted to use some other database like Sqlite or SQL Server or some other ? Well this is where <strong>dependency inversion principle</strong> comes into play. </p>
<p>To overcome this problem, we need to create an <strong>interface</strong> (abstraction or contract - see definition of DIP above) which would allow us to use <em>any database</em> with <code>User</code> class. Here is our interface that all databases would implement:</p>
<pre><code>interface DB
{
    public function connect($dsn, $user = '', $pass = '');
    public function query($query);
}</code></pre>
<p>Here is <code>Mysql</code> class now implementing above interface:</p>
<pre><code>class Mysql implements DB
{
    protected $db = null;

    public function connect($dsn, $user = '', $pass = '')
    {
        $this-&gt;db = new PDO($dsn, $user, $pass);
    }

    public function query($query)
    {
        return $this-&gt;db-&gt;query($query);
    }
}</code></pre>
<p>Another database class implementing above interface:</p>
<pre><code>class Sqlite implements DB
{
    protected $db = null;

    public function connect($dsn, $user = '', $pass = '')
    {
        $this-&gt;db = new PDO($dsn);
    }

    public function query($query)
    {
        return $this-&gt;db-&gt;query($query);
    }
}</code></pre>
<p>As you can see both <code>Mysql</code> and <code>Sqlite</code> implement methods imposed by the interface. Finally here is our <code>User</code> class:</p>
<pre><code>class User
{
    private $database = null;

    public function __construct(DB $database)
    {
        $this-&gt;database = $database;
    }

    public function getUsers()
    {
        $users = $this-&gt;database-&gt;query('SELECT * FROM users ORDER BY id DESC');
        print_r($users);
    }
}</code></pre>
<p>Notice that in constructor of above class, we are now passing interface rather than specific type of database.</p>
<p>Now we can use any database for the <code>User</code> class, here is example of <code>Mysql</code>:</p>
<pre><code>$database = new Mysql();
$database-&gt;connect('mysql:host=localhost;dbname=test', 'root', '');
$user = new User($database);
$user-&gt;getUsers();</code></pre>
<p>And example of <code>Sqlite</code> database class:</p>
<pre><code>$database = new Sqlite();
$database-&gt;connect('sqlite:database.sqlite');
$user = new User($database);
$user-&gt;getUsers();</code></pre>
<p>Amazing! we can now readily change database to be used with our <code>User</code> class, our <code>User</code> class is much more flexible by following the dependency inversion principle. If client requires to use some other database, no problem we implement one and specify to <code>User</code> class in similar fashion!</p>
<p>As you can see we took basic and common example of code and converted it into re-usable, flexible, modular and testable piece of code. </p>
<p>You might want to read more about <a href="https://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29">S.O.L.I.D principles</a> to write pleasant code and as bonus avoid <a href="http://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/">S.T.U.P.I.D</a> code.</p>]]></description>
<link>https://codeinphp.github.io/post/coding-to-interface</link>
<pubDate>Mon, 28 Dec 2015 23:45:00 +0500</pubDate>
</item>
<item>
<title>Introducing Phexecute - PHP Code Runner</title>
<description><![CDATA[<p>Some time ago I had <a href="http://codeinphp.github.io/post/phpexecute-php-code-runner/">posted about PHPExecute</a> which is PHP code runner / tester. The purpose of PHPExecute was to quickly test some PHP code and save snippets for later use. PHPExecute was very basic, I always wanted to have ability to write tests, store unlimited snippets, check coding conventions based on PSR2 but I actually never updated it to implement those features. Last weekend I sat down and wrote <strong><a href="https://github.com/sarfraznawaz2005/Phexecute">Phexecute</a></strong> , it supersedes PHPExecute. </p>
<p>Phexecute has these features:</p>
<ul>
<li>PHP Code_Sniffer to easily identify and fix problematic parts of code (through PSR-2)</li>
<li>Run PHPUnit tests and see results right inside browser</li>
<li>Run SimpleTest tests</li>
<li>Uses Symfony VarDumper component easy visualization of vars, arrays, objects</li>
<li>Ability to save unlimited snippets</li>
<li>Live PHP error highlighting</li>
<li>Easy to extend</li>
</ul>
<h2>Screenshots</h2>
<p>Main Screen</p>
<p><img src="https://raw.github.com/sarfraznawaz2005/phexecute/master/screenshots/main.png" alt="Main Window" /></p>
<p>PHP Code_Sniffer Results</p>
<p><img src="https://raw.github.com/sarfraznawaz2005/phexecute/master/screenshots/codesniffer.png" alt="CodeSniffer Window" /></p>
<p>PHPUnit Results</p>
<p><img src="https://raw.github.com/sarfraznawaz2005/phexecute/master/screenshots/phpunit.png" alt="PHPUnit Window" /></p>
<p>SimpleTest Results</p>
<p><img src="https://raw.github.com/sarfraznawaz2005/phexecute/master/screenshots/simpletest.png" alt="SimpleTest Window" /></p>
<hr />
<p><a href="https://github.com/sarfraznawaz2005/Phexecute">Checkout Phexecute on Github</a></p>]]></description>
<link>https://codeinphp.github.io/post/introducing-phexecute-php-code-runner</link>
<pubDate>Mon, 25 May 2015 13:04:00 +0500</pubDate>
</item>
<item>
<title>Slim3 Skeleton</title>
<description><![CDATA[<p>I needed to start working on some personal project which essentially isn't going to be that big. For this I was looking for light framework so I looked into <a href="http://silex.sensiolabs.org/">Silex</a>, <a href="http://lumen.laravel.com/">Lumen</a> and <a href="http://www.slimframework.com/">Slim</a>. Even though all of them do good job I however chose Slim3 to go with.</p>
<p>I had downloaded and started <em>configuring</em> Slim for my needs but then I saw a <a href="http://akrabat.com/a-slim3-skeleton/">post by Rob Allen</a> he posted yesterday mentioning that he has created Slim 3 skeleton. It was good because he already had put together all the goodies I needed:</p>
<ul>
<li>Built-in Dependency Injection Container (Slim uses Pimple DIC)</li>
<li>Monolog</li>
<li>Ability to inject middlewares</li>
<li>Twig templating engine</li>
<li>Dependency-Aware Controllers</li>
</ul>
<p>It provided good base to start with. I modified his skeleton a bit:</p>
<ul>
<li>Added <a href="http://tracy.nette.org/en/">Tracy PHP debugger</a></li>
<li>Added nice-looking interface</li>
<li>Created Twig templates with partials</li>
<li>Modified folder structure a bit so that both frontend and backend assets can easily be added and used</li>
</ul>
<p>This now allows me to easily start working on my project.</p>
<hr />
<p>Here is screenshot of default page of Slim 3 skeleton I created:</p>
<p><img src="https://codeinphp.github.io/images/1432042531555b3c238f08c.png" alt="slim-skeleton" /></p>
<hr />
<p><strong><a href="https://github.com/sarfraznawaz2005/slim3-skeleton">Slim 3 Skeleton on Github</a></strong></p>]]></description>
<link>https://codeinphp.github.io/post/slim3-skeleton</link>
<pubDate>Tue, 19 May 2015 18:57:00 +0500</pubDate>
</item>
<item>
<title>Singleton and Multiton Design Patterns</title>
<description><![CDATA[<h2>Singleton</h2>
<p>One of the simplest design patterns is the Singleton. The purpose of Singleton design pattern is to always have a <strong>single</strong> instance of a some class. Singletons are usually used for things you don't necessarily need multiple instances of such as database or logging or similar. You always work with same instance of a singleton object.</p>
<p>This is how you create a singleton:</p>
<pre><code>class MySingleton
{
    public static function getInstance()
    {
        static $instance;

        if (null === $instance) {
            $instance = new self();
        }

        return $instance;
    }

    // prevent creating multiple instances due to "private" constructor
    private function __construct(){}

    // prevent the instance from being cloned
    private function __clone(){}

    // prevent from being unserialized
    private function __wakeup(){}
}</code></pre>
<p>Usage:</p>
<pre><code>$instance = MySingleton::getInstance();</code></pre>
<p>Following the same pattern, you can create your own singletons and add any necessary functionality you want. The <strong>main</strong> trick here is that we have made the constructor <code>private</code> which is what disallows creation of multiple instances of singleton class.</p>
<p>It is important to point out that Singleton design pattern is considered anti-pattern (and more so in the world of PHP) because of following reasons:</p>
<ul>
<li>Singletons create global state which is bad; they create tight-coupling</li>
<li>Singletons are essentially class-oriented not object-oriented</li>
<li>We cannot tell what dependencies it contains, it hides logic</li>
<li>Because you cannot create multiple instances, you cannot easily test them</li>
<li>PHP runs on <a href="http://en.wikipedia.org/wiki/Shared_nothing_architecture">shared nothing architecture</a> which essentially means unlike other languages like Java/.Net, life of a PHP application is just one http request which is why singletons do not make <em>much</em> sense in PHP</li>
</ul>
<p>Having said that, many argue that you can at least use singletons for single-nature things like an instance of database or logging (though it is matter of personal preference on how you design database or logging stuff)  while others avoid singletons completely (especially <em><a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD Worshipers</a></em>).</p>
<p>That's all there is to a singleton.</p>
<h2>Multiton</h2>
<p>As the name suggests, a multiton is a design pattern that helps you create multiple instances of itself. Both singleton and multiton are same, the only difference is that a multiton can store and retrieve <em>multiple</em> instances of itself. Obviously multiton suffers from same problems as singletons.</p>
<p>Here is example of multiton:</p>
<pre><code>class Logger
{
    private static $instances = array();

    public static function getInstance($key)
    {
        if(!array_key_exists($key, self::$instances)) {
            self::$instances[$key] = new self();
        }

        return self::$instances[$key];
    }

    // prevent creating multiple instances due to "private" constructor
    private function __construct(){}

    // prevent the instance from being cloned
    private function __clone(){}

    // prevent from being unserialized
    private function __wakeup(){}
}</code></pre>
<p>Usage:</p>
<pre><code>$firstInstance = Logger::getInstance('file');
$secondInstance = Logger::getInstance('email');</code></pre>]]></description>
<link>https://codeinphp.github.io/post/singleton-and-multiton-design-patterns</link>
<pubDate>Sat, 16 May 2015 17:21:00 +0500</pubDate>
</item>
<item>
<title>Factory Design Pattern</title>
<description><![CDATA[<h2>Overview</h2>
<p>Factory design pattern works like a factory in the real world in that it creates something for others to use. In the context of OOP, it helps in creating and instantiating objects. </p>
<h2>Example</h2>
<p>Let's say for our application we are using different types of databases based on requirement such as MySQL, PostgreSQL, and SQLite. Our classes look like this:</p>
<p>MySQL:</p>
<pre><code>class MySQLDB
{
    public function setHost($host)
    {
        // code
    }
    public function setDB($db)
    {
        // code
    }
    public function setUserName($user)
    {
        // code
    }
    public function setPassword($pwd)
    {
        // code
    }
    public function connect()
    {
        // code
    }
}</code></pre>
<p>PostgreSQL:</p>
<pre><code>class PostgreSQLDB
{
    public function setHost($host)
    {
        // code
    }
    public function setDB($db)
    {
        // code
    }
    public function setUserName($user)
    {
        // code
    }
    public function setPassword($pwd)
    {
        // code
    }
    public function connect()
    {
        // code
    }
}</code></pre>
<p>...and so on for SQLite database.</p>
<p>Then we instantiate different objects based on configuration:</p>
<pre><code>if (Config::item('db_type') === 'mysql') {
    $DB = new MySQLDB();
    $DB-&gt;setHost("host");
    $DB-&gt;setDB("db");
    $DB-&gt;setUserName("user");
    $DB-&gt;setPassword("pwd");
    $DB-&gt;connect();
}
elseif (Config::item('db_type') === 'postgre') {
    $DB = new PostgreSQLDB();
    $DB-&gt;setHost("host");
    $DB-&gt;setDB("db");
    $DB-&gt;setUserName("user");
    $DB-&gt;setPassword("pwd");
    $DB-&gt;connect();
}
elseif (Config::item('db_type') === 'sqlite') {
    $DB = new SQLiteDB();
    $DB-&gt;setHost("host");
    $DB-&gt;setDB("db");
    $DB-&gt;setUserName("user");
    $DB-&gt;setPassword("pwd");
    $DB-&gt;connect();
}</code></pre>
<p>Generally above works but it creates problems in rather big applications. Above code has these problems:</p>
<ul>
<li>Should you add more database types, code would keep on growing making it complex</li>
<li>The code is hard coded with database type names</li>
<li>Whole process becomes tedious</li>
</ul>
<p>To solve these issues, we can instead create a central factory object that would create those objects for us:</p>
<pre><code>class DBFactory
{
    protected $driver = null;

    public function setDriver($driver)
    {
        $this-&gt;driver = $driver;
    }

    public function makeDB($host, $user, $pass, $dbname)
    {
        if ($this-&gt;driver === 'mysql') {
            $DB = new MySQLDB();
        }
        elseif ($this-&gt;driver === 'postgre') {
            $DB = new PostgreSQLDB();
        }
        elseif ($this-&gt;driver === 'sqlite') {
            $DB = new SQLiteDB();
        }

        $DB-&gt;setHost($host);
        $DB-&gt;setDB($dbname);
        $DB-&gt;setUserName($user);
        $DB-&gt;setPassword($pass);
        $DB-&gt;connect();

        return $DB;
    }
}</code></pre>
<p>And then using it:</p>
<pre><code>$dbFactory = new DBFactory;
$dbFactory-&gt;setDriver(Config::item('db_type'));
$DB = $dbFactory-&gt;makeDB("host", "db", "user", "pwd");</code></pre>
<p>And that's it. You won't have to modify above code, it will always remain same, we have moved the complex object creation logic separate in the factory itself which now makes our code a lot more easier to work with. </p>
<p>Please notice that there are some variations of factory design pattern such as <code>simple factory</code>, <code>abstract factory</code> and <code>factory method</code>. In this example, we used the <code>factory method</code> eg we used a <em>method</em> named <code>makeDB()</code> to create our objects. Other variations are almost similar; for example with <code>abstract factory</code>, you actually create an abstract class and then all concrete classes should extend it. It just enforces commonality between similar concrete classes.</p>
<blockquote>
<p><strong>Note:</strong> In modern day, the object creation has become very simple with the help of <a href="http://ralphschindler.com/2012/10/10/di-dic-service-locator-redux">Dependency Injection Containers and Service
Locators</a>. There are quite some <a href="http://www.sitepoint.com/php-dependency-injection-container-performance-benchmarks/">DICs to choose from for PHP</a>.</p>
</blockquote>]]></description>
<link>https://codeinphp.github.io/post/factory-design-pattern</link>
<pubDate>Fri, 15 May 2015 00:29:00 +0500</pubDate>
</item>
<item>
<title>Quick Learning Resources via StackOverflow</title>
<description><![CDATA[<p>Did you know that you that other than asking questions and answering, you can also use StackOverflow to find very useful information and learning resources for certain language or technology? Do you want to get started with some new programming language or technology ? StackOverflow can help you get started.</p>
<p>StackOverflow can help you get started by providing you with information such as history of some language/technology, books, references, commonly asked questions and tools, videos and more. Here is the format of the URL you can go to and find out useful information about certain language or technology:</p>
<p><code>http://stackoverflow.com/tags/TECHNOLOGY/info</code></p>
<p>In above URL, replace <code>TECHNOLOGY</code> with what you want to learn about such as <code>javascript</code>, <code>php</code>, <code>.net</code>, etc</p>
<p>Here are few examples:</p>
<ul>
<li><a href="http://stackoverflow.com/tags/language-agnostic/info">http://stackoverflow.com/tags/language-agnostic/info</a></li>
<li><a href="http://stackoverflow.com/tags/javascript/info">http://stackoverflow.com/tags/javascript/info</a></li>
<li><a href="http://stackoverflow.com/tags/php/info">http://stackoverflow.com/tags/php/info</a></li>
<li><a href="http://stackoverflow.com/tags/.net/info">http://stackoverflow.com/tags/.net/info</a></li>
<li><a href="http://stackoverflow.com/tags/node.js/info">http://stackoverflow.com/tags/node.js/info</a></li>
<li><a href="http://stackoverflow.com/tags/java/info">http://stackoverflow.com/tags/java/info</a></li>
<li><a href="http://stackoverflow.com/tags/android/info">http://stackoverflow.com/tags/android/info</a></li>
<li><a href="http://stackoverflow.com/tags/iphone/info">http://stackoverflow.com/tags/iphone/info</a></li>
<li><a href="http://stackoverflow.com/tags/bash/info">http://stackoverflow.com/tags/bash/info</a></li>
</ul>
<p>Of course, you can replace tag in above URL from <a href="http://stackoverflow.com/tags">various tags to choose from</a>.</p>]]></description>
<link>https://codeinphp.github.io/post/quick-learning-resources-via-stackoverflow</link>
<pubDate>Thu, 14 May 2015 22:25:00 +0500</pubDate>
</item>
<item>
<title>Creating Your Own Artisan in PHP</title>
<description><![CDATA[<p>This post is basic tutorial of how you can create your own command line tool. I will try to explain things step by step so things are easily understood.</p>
<p>When I first saw Laravel framework, I really liked its Artisan console tool, it seemed like magic providing us with a bunch of stuff we could do with it such as creating MVC triads, running migrations and a lot more. Although similar concepts already existed in frameworks like CakePHP but Laravel did good job of making us realize how useful a console app can be and that we can use it beyond basic CRUD operations.</p>
<p>To create a console app, we can use <a href="http://symfony.com/doc/current/components/console/introduction.html">Symfony's console component</a> and in fact Laravel also uses the same. We could also use <a href="https://github.com/auraphp/Aura.Cli">Aura.Cli</a> from AuraPHP but for this post, we will stick with one provided by Symfony.</p>
<h2>Installing Symfony Console Component</h2>
<p>The easiest way to install it is via composer. Create a new folder in your document root named <strong>consoleApp</strong> and inside it create <strong>composer.json</strong> file with these contents:</p>
<pre><code>{
    "require" :{
        "symfony/console": "2.6.7"
    }
}</code></pre>
<p>and then run <code>composer install</code> command in newly created folder from your cli application. After some while you should have <strong>vendor</strong> directory created. </p>
<h2>Creating Our First Command</h2>
<p>A command is something that performs an specific task. For example, in Laravel's artisan tool, you can type this:</p>
<pre><code>&gt; php artisan app:name yourAppName</code></pre>
<p>Here <code>app:name</code> is a command that can changes namespace of your Laravel application. Here is also breakdown of above line:</p>
<ul>
<li><code>php</code> - php executable (php.exe). This assumes you have already added php.exe in your <code>PATH</code> enviroment variable in your system</li>
<li><code>artisan</code> - The name of the console application</li>
<li><code>app:name</code> - The name of the command that will be run</li>
<li><code>yourAppName</code> is an argument to the <code>app:name</code> command</li>
</ul>
<p>Create a <strong>Commands</strong> folder in root of application, this will contain all our commands for the console app we will be creating. Also create empty file called <strong>app</strong> (without extension) either by using editor of your choice or running this command via your cli in app root folder <code>touch app</code>. The folder structure should now look like this:</p>
<p><img src="https://codeinphp.github.io/images/1431513018555327ba67b95.png" alt="enter image description here" /></p>
<p>Open app <code>app</code> file in editor of your choice and paste this line in it:</p>
<pre><code>#!/usr/bin/env php</code></pre>
<p>This tells the system that is a php env file and should be run by php executable. You may need to apply <em>execute</em> permission on this file if you are on Linux.</p>
<p>Next, let's include our dependencies through composer's autoload feature, so add this line:</p>
<pre><code>require __DIR__ . '/vendor/autoload.php';</code></pre>
<p>This will automatically include our dependencies which in this case is Symfony Console Component.</p>
<p>By now <code>app</code> file should have these contents:</p>
<pre><code>#!/usr/bin/env php
&lt;?php
require __DIR__ . '/vendor/autoload.php';</code></pre>
<p>Before we edit this file further, let's first create our command which will basically be a <code>Greet</code> command. Our commands will essentially be class files therefore inside Commands directory that we created earlier, create a file called <code>GreetCommand.php</code>. </p>
<p>The Symfony Console Component requires that we should extend it and provide at least two methods called <code>configure()</code> and <code>execute()</code>. As the names suggest, the <code>configure()</code> method can be used to configure our command such as what command will be called, what arguments and options it will accept and the <code>execute()</code> command will actually execute our command.</p>
<p>In <code>GreetCommand.php</code> file, paste in these contents:</p>
<pre><code>&lt;?php
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GreetCommand extends Command
{
    protected $commandName = 'app:greet';
    protected $commandDescription = "Greets Someone";

    protected $commandArgumentName = "name";
    protected $commandArgumentDescription = "Who do you want to greet?";

    protected $commandOptionName = "cap"; // should be specified like "app:greet John --cap"
    protected $commandOptionDescription = 'If set, it will greet in uppercase letters';    

    protected function configure()
    {
        $this
            -&gt;setName($this-&gt;commandName)
            -&gt;setDescription($this-&gt;commandDescription)
            -&gt;addArgument(
                $this-&gt;commandArgumentName,
                InputArgument::OPTIONAL,
                $this-&gt;commandArgumentDescription
            )
            -&gt;addOption(
               $this-&gt;commandOptionName,
               null,
               InputOption::VALUE_NONE,
               $this-&gt;commandOptionDescription
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input-&gt;getArgument($this-&gt;commandArgumentName);

        if ($name) {
            $text = 'Hello '.$name;
        } else {
            $text = 'Hello';
        }

        if ($input-&gt;getOption($this-&gt;commandOptionName)) {
            $text = strtoupper($text);
        }

        $output-&gt;writeln($text);
    }
}</code></pre>
<p>The code is pretty much self-explanatory:</p>
<ul>
<li><code>$commandName</code> is the name of our command</li>
<li><code>$commandDescription</code> is description/help text for our command</li>
<li><code>$commandArgumentName</code> is argument name of our command</li>
<li><code>$commandOptionName</code> is option name of our command. The difference between argument and option is that an option is optional one unlike argument and can be specified with <code>--optionName</code>.</li>
<li>Inside <code>configure()</code> method, we can easily understand how we set command name, argument and options. </li>
<li>Inside <code>execute()</code> method, we get argument and check to see if it is set. If set, we say <code>Hello Name</code> otherwise we simply say <code>Hello</code>. Then we check if option is provided and if so we upper case it and finally output the result.</li>
</ul>
<p>Now finally let's tell Symfony Console Component to use our command we just created. Modify <code>app</code> file so it looks like this:</p>
<pre><code>#!/usr/bin/env php
&lt;?php
require __DIR__ . '/vendor/autoload.php';

use Symfony\Component\Console\Application;

$application = new Application();

# add our commands
$application-&gt;add(new GreetCommand());

$application-&gt;run();</code></pre>
<p>Let's test our command. Open your cli app and point it to our app root and run this command:</p>
<pre><code>&gt; php app app:greet John</code></pre>
<p>That should result in error that <code>GreetCommand.php</code> flle was not found. Let's tell composer to automatically include our commands from <strong>Commands</strong> folder. Edit composer.json file so it looks like this:</p>
<pre><code>{
  "require": {
    "symfony/console": "2.6.7"
  },
  "autoload": {
    "classmap": ["Commands"]
  }
}</code></pre>
<p>and then type <code>composer dump -o</code> from your cli app. Now run our command again:</p>
<pre><code>&gt; php app app:greet John</code></pre>
<p>and you should see <code>Hello John</code>. Type:</p>
<pre><code>&gt; php app app:greet John --cap</code></pre>
<p>and you should see <code>HELLO JOHN</code>.</p>
<p>Here we named our console file <code>app</code> but if you rename it to <code>artisan</code> and then run above commands replacing <code>app</code> with <code>artisan</code>, you will have your own artisan tool, funny enough :)</p>
<p>Of course, you can now add any commands you want to your new console app. You can even run composer or git commands through your new console app or may be some deployment/build scripts or even system commands. If you are using some MVC framework, you can use this tool to for example create your own way of creating controllers, entity classes, run your custom migrations, call methods from your controllers and more.</p>
<p>If you want to see how Laravel does it all, you can take a look inside this folder and see how those commands are created:</p>
<p><code>vendor/laravel/framework/src/Illuminate/Foundation/Console</code> </p>
<p>I am currently working on a project powered by CodeIgniter (and it doesn't have built-in console app as you know) and I have created quite some commands that have really helped me speed up my development time where I do a host of different things via my console app.</p>
<p>Have fun with your artisan tool :)</p>]]></description>
<link>https://codeinphp.github.io/post/creating-your-own-artisan-in-php</link>
<pubDate>Wed, 13 May 2015 16:28:00 +0500</pubDate>
</item>
<item>
<title>Adapter Design Pattern</title>
<description><![CDATA[<h2>Overview</h2>
<p>The adapter design pattern as the name suggests is like real life adapter that converts one thing into some other one. Similarly, it can help us wrap functionality of some object into adapter providing us with consistent methods/API to work with. Understanding through an example is always the best way to learn.</p>
<h2>Example</h2>
<p>Suppose you have developed a website where client has asked you to allow users to post status updates on the Facebook. In order to to that, we use Facebook PHP client library which looks something like this:</p>
<pre><code>class Facebook {    
    public function getUserToken($userId) {
        // code to get user token
    }

    public function postUpdate($message) {
        // code to post status update
    }
}</code></pre>
<p>And then you use it to post updates on Facebook:</p>
<pre><code>$statusUpdate = new Facebook;
$statusUpdate-&gt;getUserToken($someUserId);
$statusUpdate-&gt;postUpdate('some message');</code></pre>
<p>Now let's assume suddenly client requires that instead of Facebook, he wants users to post updates on Twitter and Twitter's PHP client library looks like this:</p>
<pre><code>class Twitter {    
    public function checkUserToken($userId) {
        // code to get user token
    }

    public function setStatusUpdate($message) {
        // code to post status update
    }
}</code></pre>
<p>And here is the problem. We can see that Twitter's library has different method names which means we will have to modify code everywhere where we are using status updates. At this point, as developer, we should also not overrule the fact that client may again ask to use Facebook again or may be some other service to allow users to post status update but we don't want to change our code again and again.</p>
<p>So how do we make sure that:</p>
<ul>
<li>We should be able to add any new service easily when client asks</li>
<li>We should be able to not modify code again and again, same code should post status updates without modifying it</li>
</ul>
<p>This is where Adapter pattern comes out to be as life saver. In order to implement that, we first set rules/interface that all status update service should follow so let's create one:</p>
<pre><code>interface iStatusUpdate {
    function getUserToken($userId);
    function postUpdate($message);
}</code></pre>
<p>Now we create our Twitter adapter class:</p>
<pre><code>class TwitterAdapter implements iStatusUpdate {

    protected $twitter;

    public function __construct(Twitter $twitter){
        $this-&gt;twitter = $twitter;
    }

    public function getUserToken($userId) {
        $this-&gt;twitter-&gt;checkUserToken($userId);
    }

    public function postUpdate($message) {
        $this-&gt;twitter-&gt;setStatusUpdate($message);
    }
}</code></pre>
<p>Notice how we have passed <code>Twitter</code> object via the constructor. Of course we could have used setter or interface injection as well. </p>
<p>We can see that we now have same method names for Facebook and Twitter which means we won't have to modify much code in our codebase where we need to post status updates for users. Now all we need to do is to use our new adapter class providing it with actual Twitter object:</p>
<pre><code>$statusUpdate = new TwitterAdapter(new Twitter);
$statusUpdate-&gt;getUserToken($someUserId);
$statusUpdate-&gt;postUpdate('some message');</code></pre>
<p>As can be we have added a line or couple but most of status update code remains same, thanks to adapter pattern. We as developers should foresee such changes client may require in which case we would have created adapter class even for our first Facebook service and then we didn't need to modify even a single line of code.</p>
<p>Okay, client asks some other service to use, no problem:</p>
<pre><code>class SomeOtherServiceAdapter implements iStatusUpdate {

    protected $otherService;

    public function __construct(SomeOtherService $otherService){
        $this-&gt;otherService = $otherService;
    }

    public function getUserToken($userId) {
        $this-&gt;otherService-&gt;authenticate($userId);
    }

    public function postUpdate($message) {
        $this-&gt;otherService-&gt;postMessage($message);
    }
}</code></pre>
<p>And then:</p>
<pre><code>$statusUpdate = new SomeOtherServiceAdapter(new SomeOtherService);
$statusUpdate-&gt;getUserToken($someUserId);
$statusUpdate-&gt;postUpdate('some message');</code></pre>
<p>Again most of the code remains same. </p>
<p>So these simple examples show how useful and time-saver adapter pattern is. It provides us with consistent API to work with and allows us to use new services easily.</p>]]></description>
<link>https://codeinphp.github.io/post/adapter-design-pattern</link>
<pubDate>Mon, 11 May 2015 14:20:00 +0500</pubDate>
</item>
<item>
<title>Strategy Design Pattern</title>
<description><![CDATA[<p>In this post, we will explore what strategy design pattern is and what problems does it solve but first, what is a design pattern ? Here is how Wikipedia defines it:</p>
<blockquote>
<p>In software engineering, a design pattern is a general <strong>reusable
solution</strong> to a <strong>commonly occurring problem</strong> within a given context in
software design.</p>
</blockquote>
<p>So a design pattern is nothing but a <strong>re-usable solution towards commonly occurring problems</strong> you may face while programming.</p>
<h2>Overview</h2>
<p>One of the common problems we face in programming is to make decisions based on <em>different conditions/inputs.</em> </p>
<p>Let's say we have created a framework of our own and we want to be able to allow users to choose <em>different</em> types of logging methods such as logging to file, database or email.</p>
<h2>Example</h2>
<p>First, we create our logger classes for the framework that implement common interface:</p>
<pre><code>interface InterfaceLogger {
    function log($message);
}

class FileLogger implements InterfaceLogger {
    public function log($message) {
        // code to write logging information to file system
    }   
}

class DatabaseLogger implements InterfaceLogger {
    public function log($message) {
        // code to write logging information to database
    }   
}

class EmailLogger implements InterfaceLogger {
    public function log($message) {
        // code to write logging information to email
    }   
}</code></pre>
<p>Let's assume users of our framework are allowed to choose an specific logger through some configuration file by typing <code>file</code>, <code>database</code> or <code>email</code> and our framework is able to know it:</p>
<pre><code>$loggerType = App::getConfig('logger');</code></pre>
<p>Now we can easily find out which logger to use using strategy design pattern:</p>
<pre><code>switch($loggerType) {
    case "file":
        $logger = new FileLogger();
        break;
    case "database":
        $logger = new DatabaseLogger();
        break;
    case "email":
        $logger = new EmailLogger();
        break;
    default:
        $logger = new FileLogger();
}</code></pre>
<p>And then throughout our framework, we can use <code>$logger-&gt;log()</code> method which would automatically know which logger type to use.</p>
<p>As you might have noticed, strategy pattern is very simple one and we might have written similar code a number of times before albeit without realizing it is actually some design pattern.</p>]]></description>
<link>https://codeinphp.github.io/post/strategy-design-pattern</link>
<pubDate>Sun, 10 May 2015 17:40:00 +0500</pubDate>
</item>
<item>
<title>Replace Nested Conditions with Guard Clauses</title>
<description><![CDATA[<p>Sometimes we have to write code when we need to put conditions inside conditions (nested conditions) and once all of those are true, we perform some action. Here is dummy example of what I mean:</p>
<pre><code>function isAuthorized($userId, $age)
{
    if (isLoggedIn($userId))
    {        
        if (isAdmin($userId) &amp;&amp; $age &gt;= 18)
        {            
            if (hasAcess($userId, $resourceId))
            {
                return true;
            }
        }
    }

    return false;
}</code></pre>
<p>Although functionally nothing wrong with above code but it is good practice to avoid nested conditions (also nested loops) in some way or the other. This is simple example that may look easy to grasp to the naked eye, this isn't always the case. Obviously we can refactor above code and avoid nested conditions like this:</p>
<pre><code>function isAuthorized($userId, $age)
{
    if (isLoggedIn($userId) &amp;&amp; isAdmin($userId) &amp;&amp; $age &gt;= 18 &amp;&amp; hasAcess($userId, $resourceId))
    {        
        return true;
    }

    return false;
}</code></pre>
<p>We have shortened the code but still it doesn't look that good and readability is compromised here. Depending on the code editor/IDE you are using and font you are using or if you have even more nested conditions, this doesn't seem good solution or one that is easy to understand.</p>
<p>The solution is something called <strong>Guard Clauses</strong> which essentially mean you put your conditions in inverted way than your original conditions. Guard clauses should return opposite value compared to your original conditions. Here is how we can use guard conditions with above example:</p>
<pre><code>function isAuthorized($userId, $age)
{
    if (! isLoggedIn($userId)) { return false; }
    if (! isAdmin($userId) || $age &lt; 18) { return false; }
    if (! hasAcess($userId, $resourceId)) { return false; }

    return true;
}</code></pre>
<p>As can be seen, we have got rid of nested conditions by putting reverse conditions on top of the function. We don't proceed any further when any of these is <code>false</code>. If none is false, <code>true</code> is returned as default value in the end.</p>
<p>The benefit here is that code looks easy to understand and gives quick idea of what it is doing at first glimpse. Pretty simple yet effective stuff. </p>
<h1>Avoid This ;-)</h1>
<p><img src="https://codeinphp.github.io/images/14316395635555160b05859.png" alt="enter image description here" /></p>]]></description>
<link>https://codeinphp.github.io/post/replace-nested-conditions-with-guard-clauses</link>
<pubDate>Sat, 09 May 2015 13:53:00 +0500</pubDate>
</item>
<item>
<title>Managing Times for Users in PHP</title>
<description><![CDATA[<p>Most of the time, applications we write are meant to be used by users all over the world from different parts of the world having different time zones. Imagine a users from USA posts an status update and some other user from Asia sees completely different time even though original users might have posted status update moments ago.</p>
<p>Well the easiest way to deal with this problem would be to allow users in your application choose their timezones; for example you can present them with a dropdown of all timezones. That's first step.</p>
<p>Now once you know user's timezone, we can easily convert it back and forth. We can use GMT for this purpose because it makes it easy to convert users' timezones. So when saving times to database for example, we would first convert it to GMT. When reading from database and to show on actual webpage, we convert it from GMT to user's actual timezone. This way, we always save times in GMT and show them back to users according to their timezones.</p>
<p>I have made this simple class you can use in your applications:</p>
<pre><code>/**
 * A class to ease timezone managment for users in an applications
 *
 * @author Sarfraz Ahmed &lt;sarfraznawaz2005@gmail.com&gt;
 * @license http://www.opensource.org/licenses/mit-license.html MIT License
 */
class UserTimeZone
{

    /**
     * Time format to be used
     *
     * @var string
     */
    protected $format = null;

    /**
     * Timezone to be used
     *
     * @var string
     */
    protected $defaultTimeZone = null;

    /**
     * @param string $format
     * @param string $defaultTimeZone
     */
    public function __construct($format = 'Y-m-d h:i:s P', $defaultTimeZone = 'UTC')
    {
        $this-&gt;format = $format;
        $this-&gt;defaultTimeZone = $defaultTimeZone;
    }

    /**
     * Returns all timezones in an array.
     * Can be used to construct a dropdown of all timezones
     * for users to select
     *
     * @return array
     */
    public function getTimeZones()
    {
        return DateTimeZone::listIdentifiers();
    }

    /**
     * Sets dates in GMT format.
     * Should be used when saving dates in database for example.
     *
     * @param $date
     * @return string
     */
    public function setDate($date)
    {
        $date = new DateTime($date, new DateTimeZone($this-&gt;defaultTimeZone));
        $date-&gt;setTimezone(new DateTimeZone('GMT'));

        return $date-&gt;format($this-&gt;format);
    }

    /**
     * Gets data based on users' timezones.
     * Should be used when showing dates in pages for example.
     *
     * @param $date
     * @return string
     */
    public function getDate($date)
    {
        $date = new DateTime($date, new DateTimeZone('GMT'));
        $date-&gt;setTimezone(new DateTimeZone($this-&gt;defaultTimeZone));

        return $date-&gt;format($this-&gt;format);
    }
}</code></pre>
<p>It is self-explanatory. Read the comments in class please.</p>
<p>Usage:</p>
<pre><code>$format = 'd-m-Y h:i:s';
$userTZ = 'Asia/Karachi'; // user's time zone
$tz = new UserTimeZone($format, $userTZ);

$date = $tz-&gt;setDate('2015-01-01 6:32 PM');
// save $date in db for example

$date = $tz-&gt;getDate('2015-01-01 9:32 PM');
// show $date on webapge for example</code></pre>]]></description>
<link>https://codeinphp.github.io/post/managing-times-for-users-in-php</link>
<pubDate>Tue, 05 May 2015 13:31:00 +0500</pubDate>
</item>
<item>
<title>Semantic Versioning and Composer</title>
<description><![CDATA[<p>Today any seriously written application/software follows the <em><a href="http://semver.org/">Semantic Versioning</a></em> (also called <em>SemVer</em>). It boils down to this (emphasis mine):</p>
<ol>
<li>MAJOR version when you make <strong>incompatible API changes</strong></li>
<li>MINOR version when you add functionality in a <strong>backwards-compatible</strong> manner</li>
<li>PATCH version when you make <strong>backwards-compatible bug fixes</strong></li>
</ol>
<p>Let's take example of <a href="http://symfony.com/">Symfony</a> framework which follows SemVer. As of this writing, its stable version stands at <code>2.6.6</code></p>
<p><strong>Symfony Versioning</strong></p>
<pre>
+-------+---------+
| Name  | Version |
+-------+---------+
| MAJOR | 2       |
+-------+---------+
| MINOR | 6       |
+-------+---------+
| PATCH | 6       |
+-------+---------+
</pre>
<p>Here, we can see that MINOR and PATCH versions are  backwards-compatible. This means if you install Symfony version <code>2.0.0</code> or <code>2.x.x</code> with <code>x</code> being any number, it will be backwards-compatible. Meaning if you had initially installed Symfony version <code>2.0.0</code> and now you want to install version <code>2.6.6</code>, you can do so <strong>without worrying</strong> it breaking functionality. However when Symfony announces a version starting with <code>3</code> as MAJOR version then it will most likely break some of the functionality with all previous version  less than <code>3.x.x</code>.  Thanks to SemVer, we can easily find that out now. Not to mention, almost all nicely written frameworks or libraries or software in general now follow SemVer. <a href="http://semver.org/">Please read more about it</a>.</p>
<p>As a PHP developer, <a href="https://getcomposer.org/">composer</a> is something we can't do without these days. If you think you are a PHP developer and haven't started using composer yet, you are not a PHP developer DOT In that case, search on Google on what it is and its tutorials or see its <a href="https://getcomposer.org/doc/">official documentation</a>.  In short, it is package manager for PHP that has superseded older methods such as PEAR, etc. It is like NPM for NodeJS or RubyGem for Ruby developers.</p>
<p>Let's say I want to install Symfony via composer, I can specify specific version to use in quite some ways like:</p>
<pre>
+--------------------------------+----------------------------------------------------------------+
| Version                        | Description                                                    |
+--------------------------------+----------------------------------------------------------------+
| symfony/symfony: "2.6.6"       | Exact 2.6.6 version                                            |
+--------------------------------+----------------------------------------------------------------+
| symfony/symfony: ">= 2.6"      | Any version greater than or equal to 2.6 like 2.6.7, 6.6.9     |
+--------------------------------+----------------------------------------------------------------+
| symfony/symfony: ">= 2.6,<3.0" | Any version greater than or equal to 2.6 but less than 3 Major |
+--------------------------------+----------------------------------------------------------------+
| symfony/symfony: "2.*"         | Any version as long as Major version is 2                      |
+--------------------------------+----------------------------------------------------------------+
| symfony/symfony: "*"           | Latest version                                                 |
+--------------------------------+----------------------------------------------------------------+
| symfony/symfony: "dev-master"  | Latest version from "master" branch                            |
+--------------------------------+----------------------------------------------------------------+
| symfony/symfony: "dev-testing" | Latest version from "testing" branch                           |
+--------------------------------+----------------------------------------------------------------+
</pre>
<p>We can also use special tilde character <code>~</code>:</p>
<pre>
+---------------------------+-----------------------------------------------------------------------+
| Version                   | Description                                                           |
+---------------------------+-----------------------------------------------------------------------+
| symfony/symfony: "~2.6.6" | Any version starting from 2.6.0 to 2.6.x with x being any number      |
+---------------------------+-----------------------------------------------------------------------+
| symfony/symfony: "~2.6"   | Any version starting from 2.0 to 2.x or 2.x.x with x being any number |
+---------------------------+-----------------------------------------------------------------------+
| symfony/symfony: "~2"     | Any Major version greater than or equal to 2 like 2.x or 5.x.x        |
+---------------------------+-----------------------------------------------------------------------+
</pre>
<p>Once you know how to specify versions in composer, you can easily make sure you are only installing those packages that are <strong>backwards-compatible</strong> unless you want fresh installation of some package. Similarly, if you have wrote some package, you should choose versioning sensibly so that users of your package don't go <strong>incompatible</strong> accidentally if you have not made Major changes to your package.</p>
<hr />
<p>By the way, here is extremely useful <a href="http://composer.json.jolicode.com/">Composer cheat sheet</a>, have fun !</p>]]></description>
<link>https://codeinphp.github.io/post/semantic-versioning-and-composer</link>
<pubDate>Thu, 30 Apr 2015 00:53:00 +0500</pubDate>
</item>
<item>
<title>Throwing Your Own Library Exceptions in PHP</title>
<description><![CDATA[<p>In the <a href="http://codeinphp.github.io/post/exceptions-are-bad-yet-awesome/">previous post</a>, we saw the difference between errors and exceptions, how exceptions can be useful and created our custom exception handler. In this post, we will look how we can create custom exceptions specific to our application, library or company. We also talk about <a href="http://php.net/manual/en/spl.exceptions.php">SPL Exceptions</a> that should be used in your code where possible as best practice.</p>
<h2>Background</h2>
<p>Let's start with bit of background. If you worked on PHP's DOM, PDO, MySQLi or some other extensions or frameworks such as Symphony, Laravel, Slim or any other third party libraries, you might have noticed usually they throw their own exceptions:</p>
<pre><code>$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

$dbh = new PDO($dsn, $user, $password);
$dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);</code></pre>
<p>In case of wrong database connection, it would throw <code>PDOException</code>:</p>
<pre><code>PDOException: SQLSTATE[HY000] [1045] Access denied for user 'dbuser'@'localhost'</code></pre>
<p>Where did <code>PDOException</code> come from ? Or how did PDO gave that exception ? It is simple. As I had pointed out in my <a href="http://codeinphp.github.io/post/exceptions-are-bad-yet-awesome/">previous post</a>, <a href="http://php.net/manual/en/class.exception.php"><code>Exception</code></a> is a class like any other normal class that can be <a href="http://php.net/manual/en/language.exceptions.extending.php">extended</a>. That's exactly what PDO does here, it simply <code>extends</code> the <code>Exception</code> class so PDO extension should be doing something like this under the hood to be able to throw <code>PDOException</code>:</p>
<pre><code>class PDOException extends Exception {}</code></pre>
<p>And that's <em>usually</em> it. And then PDO should now be throwing that new exception instead of <code>Exception</code>:</p>
<pre><code>// something went wrong
throw new PDOException('message here');</code></pre>
<p>And then user of PDO sees those <code>PDOExceptions</code>.</p>
<p>Now that we know <code>PDOException</code> actually extends <code>Exception</code>, we can come to conclusion that we can catch exceptions thrown by PDO either by using <code>PDOException</code> or <code>Exception</code> through <em>nested</em> catch blocks. If exception is NOT caught for <code>PDOException</code>, it will fall back to base <code>Exception</code>:</p>
<pre><code>try{
    // any PDO code here
}
catch(PDOException $e){
    // handle PDOException
}
catch(Exception $e){
    // handle Exception
}</code></pre>
<h2>Throwing Your Own Exceptions</h2>
<p>As said above, we can throw our own exceptions by extending the <code>Exception</code> class:</p>
<pre><code>class MyAwesomeLibraryException extends Exception {}</code></pre>
<p>or</p>
<pre><code>class MyCompanyException extends Exception {}</code></pre>
<p>That's easy but one might ask why throw custom exceptions? I can see these reasons:</p>
<ul>
<li>It makes it easy to recognize which thing (library, class, extension, etc) generated exception in code hierarchy</li>
<li>This helps developer of orginal library easily spot problems in their code</li>
<li>It brands your library exceptions like PDO, DOM, etc do.</li>
</ul>
<p>Now as developer of some library/application, any time we find we need to throw exception, we simply throw our own custom exceptions:</p>
<pre><code>// something wrong, throw our custom exception
throw new MyAwesomeLibraryException('some message');</code></pre>
<p>Of course you can have many exception types as well for your application if you want.</p>
<h2>Prioritizing Your Own Exceptions</h2>
<p>Imagine we want to create our own ORM library called <strong>SuperORM</strong> and it uses PDO under the hood. We create our custom exception first:</p>
<pre><code>class SuperORMException extends PDOException {}</code></pre>
<p>And now we throw <code>SuperORMException</code> exception from whole of our ORM where needed. But since we are using PDO under the hood, we get its <code>PDOException</code> as well and we don't want to show this <em>directly</em> to the consumers of our SuperORM library, we want to be able to first show them our own exception type. This is how we can do that:</p>
<pre><code>class SuperORMException extends PDOException {}

class SuperORM {
    public function connect($dsn, $user, $password) {
        // try connecting to database
        try {
            $dbh = new PDO($dsn, $user, $password);
            $dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch (PDOException $e) {
            throw new SuperORMException($e-&gt;getMessage(), null, $e);
        }        
    }
}

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

$superORM = new SuperORM;
$superORM-&gt;connect($dsn, $user, $password);</code></pre>
<p>And that would result in our <code>SuperORMException</code>:</p>
<p><code>SuperORMException: SQLSTATE[HY000] [1045] Access denied for user 'dbuser'@'localhost'</code></p>
<p>And consumer of our SuperORM can catch our exception now:</p>
<pre><code>try {
    $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
    $user = 'dbuser';
    $password = 'dbpass';

    $superORM = new SuperORM;
    $superORM-&gt;connect($dsn, $user, $password);
}
catch (SuperORMException $e) {
    echo $e-&gt;getMessage();
}</code></pre>
<p>This makes sure consumer of library will now know that SuperORM will always throw exception of type <code>SuperORMException</code>.</p>
<p>We see that <code>SuperORMException</code> extends <code>PDOException</code> and <code>PDOException</code> extends <code>Exception</code>, this gives consumer the opportunity to catch exceptions in those types like so:</p>
<pre><code>try {
    $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
    $user = 'dbuser';
    $password = 'dbpass';

    $superORM = new SuperORM;
    $superORM-&gt;connect($dsn, $user, $password);
}
catch (SuperORMException $e) {
    // code to catch exception
}
catch (PDOException $e) {
    // code to catch exception
}
catch (Exception $e) {
    // code to catch exception
}</code></pre>
<p>So that's how you can throw your own custom exceptions. In fact that's how some of the ORMs or database libraries from various framework do and throw their own exceptions for consumers to catch.</p>
<h2>Don't Always Throw Your Custom Exceptions</h2>
<p>By this I mean there are certain exceptions types that are part of Standard PHP (SPL) known as <a href="http://php.net/manual/en/spl.exceptions.php">SPL Exceptions</a>. They are made to be thrown for <em>specific</em> reasons and considered best practice. You should throw SPL Exceptions <em>where applicable</em> instead of your own custom exceptions. Here they are:</p>
<ul>
<li><a href="http://php.net/manual/en/class.logicexception.php">LogicException</a> (extends <a href="http://php.net/manual/en/class.exception.php">Exception</a>)
<ul>
<li><a href="http://php.net/manual/en/class.badfunctioncallexception.php">BadFunctionCallException</a>
<ul>
<li><a href="http://php.net/manual/en/class.badmethodcallexception.php">BadMethodCallException</a></li>
</ul></li>
<li><a href="http://php.net/manual/en/class.domainexception.php">DomainException</a></li>
<li><a href="http://php.net/manual/en/class.invalidargumentexception.php">InvalidArgumentException</a></li>
<li><a href="http://php.net/manual/en/class.lengthexception.php">LengthException</a></li>
<li><a href="http://php.net/manual/en/class.outofrangeexception.php">OutOfRangeException</a></li>
</ul></li>
<li><a href="http://php.net/manual/en/class.runtimeexception.php">RuntimeException</a> (extends <a href="http://php.net/manual/en/class.exception.php">Exception</a>)
<ul>
<li><a href="http://php.net/manual/en/class.outofboundsexception.php">OutOfBoundsException</a></li>
<li><a href="http://php.net/manual/en/class.overflowexception.php">OverflowException</a></li>
<li><a href="http://php.net/manual/en/class.rangeexception.php">RangeException</a></li>
<li><a href="http://php.net/manual/en/class.underflowexception.php">UnderflowException</a></li>
<li><a href="http://php.net/manual/en/class.unexpectedvalueexception.php">UnexpectedValueException</a></li>
</ul></li>
</ul>
<p>As can be seen, those exceptions can be broadly divided into two main categories: <code>LogicException</code> and <code>RuntimeException</code>. All of those exceptions are self-explanatory from their names. For example <code>LogicException</code> represent any errors caused by the logical errors in your code,  <code>RuntimeException</code> represent any errors that are caused after script has run eg runtime errors; similarly <code>BadMethodCallException</code> exception should be thrown if a method in your class doesn't exist and so on.</p>
<p>These SPL exceptions are excellent addition to PHP core because previously if call was made to some method which didn't exist, you usually communicated that to user through a message like:</p>
<pre><code>throw new Exception('Method does not exist!');</code></pre>
<p>So you communicated through those messages for different types of problems. The problem here was that we needed specific exceptions; if method didn't exist, we needed <code>BadMethodCallException</code> exception. This clearly tells developer what type of exception it is and <em>why</em> it might have come about. Another benefit is that such exceptions are useful even for Non-English speaking developers who can also easily spot the problem. Therefore, you must use SPL exceptions for different situations they are made for.</p>]]></description>
<link>https://codeinphp.github.io/post/throwing-your-own-library-exceptions-in-php</link>
<pubDate>Mon, 27 Apr 2015 18:06:00 +0500</pubDate>
</item>
<item>
<title>Exceptions Are Bad Yet Awesome!</title>
<description><![CDATA[<h2>Overview</h2>
<p>At first thought, the words <strong>errors</strong> and <strong>exceptions</strong> give the general idea that they are the same thing or collectively <em>errors</em> especially to the beginners. For example, when we see this:</p>
<p><code>Fatal error: Call to undefined method Foo::bar()</code></p>
<p>Or this:</p>
<p><code>Exception: Method is not callable by this object</code></p>
<p>Most beginner developer would concluded that those are just errors that need to be fixed and that may be right in a superficial sense because both of those messages are bad and need to be fixed anyway but in reality they are different things. The first one is an <strong>Error</strong> while later one is an <strong>Exception</strong>. Once we understand there can be <em>both errors and exceptions</em> and how to successfully handle each, we can surely write better code. </p>
<p>In this post, we will see how we can deal with both of them and even create our own custom error and exception handlers for more control over how we want them to be displayed or handled while following best practices.</p>
<h1>Difference between Errors and Exceptions</h1>
<p><strong>Errors</strong></p>
<ul>
<li>
<p>Errors are errors that are emitted by the programming language and you need to fix them. </p>
</li>
<li>
<p>There can be syntax errors or logic errors. In PHP, there are different <em>levels</em> of errors such as <code>ERROR</code>, <code>PARSE</code>, <code>WARNING</code>, <code>NOTICE</code>, <code>STRICT</code>. Some errors levels halt the further execution of your PHP script (such as <code>FATAL</code> errors) while others allow it to continue while presenting useful information that might also need to be fixed or payed attention to such as <code>WARNING</code> or <code>NOTICE</code>. And finally there are other error levels that can tell whether a particular function is deprecated (<code>DEPRECATED</code>) or whether or not standards are being followed (<code>STRICT</code>).</p>
</li>
<li>
<p>Errors can be converted into user-thrown exceptions while still some being recoverable other not because they are emitted by core programming language</p>
</li>
<li>
<p>We can emit custom/user errors through <a href="http://php.net/manual/en/function.trigger-error.php"><code>trigger_error()</code></a> function</p>
</li>
<li>
<p>We can create custom error handler for all errors using <a href="http://php.net/manual/en/function.set-error-handler.php"><code>set_error_handler()</code></a></p>
</li>
<li>The <a href="http://php.net/manual/en/function.error-get-last.php"><code>error_get_last</code></a> function can be used to get any error that happened last in PHP code. The <a href="http://php.net/manual/en/reserved.variables.phperrormsg.php"><code>$php_errormsg</code></a> variable can be used to get previous error message.</li>
</ul>
<p><strong>Exceptions</strong>:</p>
<ul>
<li>
<p>Exceptions are object oriented approach to errors and are thrown intentionally by code/developer and should be handled/caught using <code>try - catch -finally</code> blocks</p>
</li>
<li>
<p>An <code>Exception</code>is a standard class that can be used like any other class and can also be extended.</p>
</li>
<li>
<p>Exceptions can have many types (through sub-classes) while errors can only have levels mentioned above.</p>
</li>
<li>
<p>Exceptions can be caught at any point in the call stack and can also be caught at root/default exception handler. In comparison, errors are only handled in pre-defined error handler.</p>
</li>
<li>
<p>We can throw custom/user exceptions by using <code>throw new Exception(...)</code></p>
</li>
<li>We can create custom exception handler for all exceptions using <a href="http://php.net/manual/en/function.set-exception-handler.php"><code>set_exception_handler()</code></a></li>
</ul>
<h2>General Practice</h2>
<p>Nowadays, it seems common (and better) practice to always throw exceptions (even for errors) from your code so that they can be caught and dealt with in caller script. Of course if we throw an exception for error which is <code>FATAL</code>, we can't recover from it but we can still provide OOP approach to caller script. If you have used <code>MySQL</code> extension, you would notice that it emits normal errors if something goes wrong; here is an example when connection to database could not be made:</p>
<p><code>Warning: mysql_connect(): Access denied for user 'root'@'localhost'</code></p>
<p>Notice that it emits error level of <code>Warning</code>. This is just an example for the function <code>mysql_connect</code> but other functions of <code>MySQL</code> extension also emit errors in the same way and can be grabbed with <a href="http://php.net/manual/en/function.mysql-error.php"><code>mysql_error()</code></a> function.</p>
<p>But if you use improved version of MySQL called <code>MySQLi</code> or even <code>PDO</code>, you would notice they can now also throw exceptions, here is same example if connection could not be made to database using <code>mysqli</code>:</p>
<pre><code>mysqli_report(MYSQLI_REPORT_STRICT); // tell mysqli to generate exceptions as well
mysqli_connect('localhost', 'root', 'wrongPassword', 'test');</code></pre>
<p>It would give you both error as well as exception:</p>
<p><code>Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Access denied for user 'root'@'localhost'</code></p>
<p><code>mysqli_sql_exception: Access denied for user 'root'@'localhost' (using password: YES)</code></p>
<p>So these days any good written package or library or some extension you use, it would most likely generate Exceptions of its own type so that they can be caught and handled gracefully.</p>
<h2>How Do Exceptions Help ?</h2>
<p>Let's understand through example. Let's say you want to connect to database using <code>mysql</code> and you would normally do something like this:</p>
<pre><code>mysql_connect('localhost', 'root', 'wrongPassword', 'test');</code></pre>
<p>If connection could not be made to database, you would receive error:</p>
<p><code>Warning: mysql_connect(): Access denied for user 'root'@'localhost'</code></p>
<p>Now the <strong><em>only</em></strong> thing you can do is go to your code and edit it to specify correct database credentials. </p>
<p>Let's now do the same thing using <code>mysqli</code>:</p>
<pre><code>mysqli_report(MYSQLI_REPORT_STRICT); // tell mysqli to generate exceptions as well
mysqli_connect('localhost', 'root', 'wrongPassword', 'test');</code></pre>
<p>This would generate an error as well as exception as shown previously. Since exception is generated, we can catch it and show the message:</p>
<pre><code>try {    
    mysqli_connect('localhost', 'root', 'wrongPassword', 'test');
} catch (mysqli_sql_exception $e) {
    echo $e-&gt;getMessage();
}</code></pre>
<p>The reason why exception is useful here is because you are given a chance to catch that exception gracefully. Inside <code>catch</code> block, we can handle the exception however we want. For the sake of example, let's say we want to connect to database again with correct password this time:</p>
<pre><code>mysqli_report(MYSQLI_REPORT_STRICT);

try {    
    mysqli_connect('localhost', 'root', 'wrongPassword', 'test');
} catch (mysqli_sql_exception $e) {
    mysqli_connect('localhost', 'root', 'rightPassword', 'test');
}</code></pre>
<p>And thanks to exception, we were able to catch it and handle it the way we needed and we are now connected to database which was simply not possible with previous example using <code>mysql</code> which only emitted an error and we couldn't do much. Of course in real world applications, you might not have different passwords to connect to database but this example just gives an idea of <em>how</em> exceptions can be useful.</p>
<p>As another example, let's say we want read feed/rss of some website using <a href="http://php.net/manual/en/book.simplexml.php">SimpleXML</a> (which can also throw exceptions) and store 10 posts in an array:</p>
<pre><code>$feedUrl = 'http://some_feed_url';
$feeds = file_get_contents($feedUrl);
$xml = new SimpleXmlElement($feeds);

$articles = array();
foreach ($xml-&gt;channel-&gt;item as $item) {
   $item = (array) $item;
   $articles[] = array('title' =&gt; $item['title'], 'link' =&gt; $item['link']);
}

$data['articles'] = array_slice($articles, 0, 10);</code></pre>
<p>This would work as long as feed url is correct and has posts but if url is wrong, you would see a <code>Fatal</code> error as well <code>Exception</code> being generated by the script:</p>
<p><code>Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML</code></p>
<p><code>Exception: String could not be parsed as XML</code></p>
<p>Since it is <code>FATAL</code> error, our script died at that point and we can't do anything. How do we ensure that our script continues working and runs any code below that feed code even if provided feed url was wrong ? Of course we need to <code>catch</code> the exception since as we saw it also generated an <code>Exception</code>:</p>
<pre><code>try {
    $feedUrl = 'http://some_feed_url';
    $feeds = file_get_contents($feedUrl);
    $xml = new SimpleXmlElement($feeds);

    $articles = array();
    foreach ($xml-&gt;channel-&gt;item as $item) {
       $item = (array) $item;
       $articles[] = array('title' =&gt; $item['title'], 'link' =&gt; $item['link']);
    }

    $data['articles'] = array_slice($articles, 0, 10);
} catch (Exception $e) {

}

echo 'Hello World';</code></pre>
<p>And now since we have wrapped our code in <code>try-catch</code> and caught the exception, our code below that should still run. In this case even if feed url was wrong, you should still see the <code>Hello World</code> message. Our script didn't die and continued its execution. So those two examples should now give idea of how useful exceptions can be when used.</p>
<h2>How do I convert Errors into Exceptions?</h2>
<p>To do so ,we can use the <a href="http://php.net/manual/en/function.set-error-handler.php"><code>set_error_handler()</code></a> function and throw exceptions of type <a href="http://php.net/manual/en/class.errorexception.php"><code>ErrorException</code></a> something like:</p>
<pre><code>set_error_handler(function ($errorNumber, $errorText, $errorFile, $errorLine ) 
{
    throw new ErrorException($errorText, 0, $errorNumber, $errorFile, $errorLine);
});</code></pre>
<p>With that custom exception now in place, you can do things like:</p>
<pre><code>try {
    // wrong url
    file_get_contents('http://wrong_url');
} catch (ErrorException $e) {
    // fix the url
    file_get_contents('http://right_url');
}</code></pre>
<p>So in <code>catch</code> block, we are now able to fix the URL for the <code>file_get_contents</code> function. Without this exception, we could do nothing but may be suppressing the error by using <a href="http://php.net/manual/en/language.operators.errorcontrol.php">error control operator @</a>.</p>
<h2>Universal Exception Handler</h2>
<p>Now that we have seen how useful exceptions are and how to convert errors into exceptions, we can create our custom universal exception handler that can be used throughout the application. It will always generate exceptions not errors. It will do these things:</p>
<p>1 - Allow us to tell it our environment which can be either <code>development</code> or <code>production</code></p>
<p>2 - In case of <code>production</code> environment, it will log all errors to a file instead of displaying them on screen</p>
<p>3 - In case of <code>development</code> environment, it will display all errors on the screen</p>
<pre><code>/**
 * A class that handles both errors and exceptions and generates an Exception for both.
 *
 * In case of "production" environment, errors are logged to file
 * In case of "development" environment, errors are echoed out on screen
 *
 * Usage:
 *
 * new ExceptionHandler('development', '/myDir/logs');
 *
 * Note: Make sure to use it on very beginning of your project or bootstrap file.
 *
 */
class ExceptionHandler {
    // file path where all exceptions will be written to
    protected $log_file = '';
    // environment type
    protected $environment = '';

    public function __construct($environment = 'production', $log_file = 'logs')
    {
        $this-&gt;environment = $environment;
        $this-&gt;log_file = $log_file;

        // NOTE: it is better to set ini_set settings via php.ini file instead to deal with parse errors.
        if ($this-&gt;environment === 'production') {
            // disable error reporting
            error_reporting(0);
            ini_set('display_errors', false);
            // enable logging to file
            ini_set("log_errors", true);
            ini_set("error_log", $this-&gt;log_file);
        }
        else {
            // enable error reporting
            error_reporting(E_ALL);
            ini_set('display_errors', 1);
            // disable logging to file
            ini_set("log_errors", false);
        }

        // setup error and exception handlers
        set_error_handler(array($this, 'errorHandler'));
        set_exception_handler(array($this, 'exceptionHandler'));        
    }

    public function exceptionHandler($exception)
    {
        if ($this-&gt;environment === 'production') {
            error_log($exception, 3, $this-&gt;log_file);
        }

        throw new Exception('', null, $exception);
    }

    public function errorHandler($error_level, $error_message, $error_file, $error_line)
    {
        if ($this-&gt;environment === 'production') {      
            error_log($message, 3, $this-&gt;log_file);
        }

        // throw exception for all error types but NOTICE and STRICT
        if ($error_level !== E_NOTICE &amp;&amp; $error_level !== E_STRICT) {
            throw new ErrorException($error_message, 0, $error_level, $error_file, $error_line);
        }        
    }
}</code></pre>
<p>Test it:</p>
<pre><code>// register our error and exceptoin handlers
new ExceptionHandler('development', 'logs');

// create error and exception for testing
trigger_error('Iam an error but will be converted into ErrorException!');
throw new Exception('I am an Exception anyway!');</code></pre>
<p>So that is an example of <em>basic</em> universal error and exception handler class. Actually you can do a lot more like customizing the display of messages, getting the stack trace as well as code that caused it, creating timestamp for when those events take place, etc. You should checkout the official documentation in order to achieve those goodies. At any point in your code, you want to restore original PHP's error and exception handlers, you can use <a href="http://php.net/manual/en/function.restore-error-handler.php"><code>restore_error_handler()</code></a> and <a href="http://php.net/manual/en/function.restore-exception-handler.php"><code>restore_exception_handler()</code></a> functions.</p>
<h2>Conclusion</h2>
<p>No exception to exceptions!</p>
<hr />
<p>As a side note, I personally hope someday a PSR standard is created for handling errors and exceptions and their best practices because they are integral part of any PHP code.</p>]]></description>
<link>https://codeinphp.github.io/post/exceptions-are-bad-yet-awesome</link>
<pubDate>Mon, 27 Apr 2015 02:09:00 +0500</pubDate>
</item>
<item>
<title>CodeIgniter Tip: Accessing CodeIgniter Instance Outside</title>
<description><![CDATA[<p>Sometimes you need to access CodeIgniter application instance completely outside of it, may be in Ajax request or an script which is not part of your main CI application. To do so, you can do this:</p>
<pre><code>// file: CI.php
ob_start();
require_once 'index.php'; // adjust path accordingly
ob_get_clean();
return $CI;</code></pre>
<p>Here we are including <code>index.php</code> file of main CI application. We are using buffering functions here so we don't see actual CI application page and finally we we <code>return</code> the <code>$CI</code> instance so that in any page where we need CI instance, we can simply include this file there. So to use it in some other script, you would simply include above file there:</p>
<pre><code>$CI = require_once 'CI.php';
echo $CI-&gt;config-&gt;item('base_url'); // test CI instance</code></pre>
<p>That should work for the most cases.</p>
<p>I happen to need CI instance in a cli/console application but above method didn't do the trick for me in console app. So here is another very very hacky way of getting instance of CI in a console app that I was able to come up with after analyzing CodeIgniter code:</p>
<pre><code>// Hacky Way of Accessing CI Instance Outside

error_reporting(1);

$environment = 'development';

$system_path = 'system';

$application_folder = 'application';

if (realpath($system_path) !== false) {
    $system_path = realpath($system_path) . '/';
}

$system_path = rtrim($system_path, '/') . '/';

define('BASEPATH', str_replace("\\", "/", $system_path));
define('APPPATH', $application_folder . '/');
define('EXT', '.php');
define('ENVIRONMENT', $environment ? $environment : 'development');

require(BASEPATH .'core/Common.php');

if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/constants.php')) {
    require(APPPATH.'config/'.ENVIRONMENT.'/constants.php');
} else {
    require(APPPATH.'config/constants.php');
}

$GLOBALS['CFG'] =&amp; load_class('Config', 'core');
$GLOBALS['UNI'] =&amp; load_class('Utf8', 'core');

if (file_exists($basepath.'core/Security.php')) {
  $GLOBALS['SEC'] =&amp; load_class('Security', 'core');
}

load_class('Loader', 'core');
load_class('Router', 'core');
load_class('Input', 'core');
load_class('Lang', 'core');

require(BASEPATH . 'core/Controller.php');

function &amp;get_instance() {
    return CI_Controller::get_instance();
}

$class = 'CI_Controller';
$instance = new $class();

return $instance;</code></pre>
<p>As said above, this is extremely hacky way and may or may not work in all cases and you would also need to adjust paths in above code and/or load more libraries/helpers/etc you need by modifying it.</p>]]></description>
<link>https://codeinphp.github.io/post/codeigniter-tip-accessing-codeigniter-instance-outside</link>
<pubDate>Sun, 26 Apr 2015 02:17:00 +0500</pubDate>
</item>
<item>
<title>Sharing Functionality Using Traits in PHP</title>
<description><![CDATA[<p>Official <a href="http://php.net/manual/en/language.oop5.traits.php">documentation</a> defines traits as:</p>
<blockquote>
<p>Traits are a mechanism for code reuse in single inheritance languages
such as PHP. A Trait is intended to reduce some limitations of single
inheritance by enabling a developer to reuse sets of methods freely in
several independent classes living in different class hierarchies. The
semantics of the combination of Traits and classes is defined in a way
which reduces complexity, and avoids the typical problems associated
with multiple inheritance and Mixins.</p>
</blockquote>
<p>So what does this mean ? Let's understand through practical example. Imagine we have chat application and database contains two tables; <code>users</code> and <code>messages</code> and we want to be able to have <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> functionality for each of those entities. Here is how model class for <code>User</code> looks:</p>
<pre><code>class User {
    protected $table = 'users';

    public function getAll() {
        return DB::getAll($this-&gt;table);
    }

    public function get($id) {
        return DB::get($this-&gt;table, $id);
    }

    public function add($data) {
        return DB::add($this-&gt;table, $data);
    }

    public function update($id) {
        return DB::update($this-&gt;table, $id);
    }

    public function remove($id) {
        return DB::remove($this-&gt;table, $id);
    }
}</code></pre>
<p><code>Message</code> model class:</p>
<pre><code>class Message {
    protected $table = 'messages';

    public function getAll() {
        return DB::getAll($this-&gt;table);
    }

    public function get($id) {
        return DB::get($this-&gt;table, $id);
    }

    public function add($data) {
        return DB::add($this-&gt;table, $data);
    }

    public function update($id) {
        return DB::update($this-&gt;table, $id);
    }

    public function remove($id) {
        return DB::remove($this-&gt;table, $id);
    }
}</code></pre>
<p>At first glance, we can see that both of these classes have exactly the same code for those five methods with only difference of <code>$table</code> being different. This smells and to follow the principle of <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">Don't Repeat Yourself</a>, we can use inheritance of course. So we create a new abstract class that will contain common functionality in the form of those five methods and then both classes would extend this base class:</p>
<pre><code>abstract class Model {     
    public function getAll() {
        return DB::getAll($this-&gt;table);
    }

    public function get($id) {
        return DB::get($this-&gt;table, $id);
    }

    public function add($data) {
        return DB::add($this-&gt;table, $data);
    }

    public function update($id) {
        return DB::update($this-&gt;table, $id);
    }

    public function remove($id) {
        return DB::remove($this-&gt;table, $id);
    }
}</code></pre>
<p>And now our <code>User</code> and <code>Message</code> classes look like this:</p>
<pre><code>class User extends Model {
    protected $table = 'users';
}

class Message extends Model {
    protected $table = 'messages';
}</code></pre>
<p>And that's it, now both of these classes inherit those five methods from the base <code>Model</code> class, no need to repeat them now, perfect !</p>
<p>Now imaging that suddenly clients requires that some of the fields in both of those tables should be encrypted. For that we create a class that contains two methods <code>encrypt()</code> and <code>decrypt()</code>:</p>
<pre><code>class Encoder {
    public static function encrypt($text, $key) {
        // code to encrypt text
    }

    public static function decrypt($text, $key) {
        // code to decrypt text
    } 
}</code></pre>
<p>But how do we use it now ? First thought would be to use it as needed:</p>
<pre><code>$user = new User();
$user-&gt;add(array('email' =&gt; 'foo@bar.com', 'password' =&gt; Encoder::encrypt('some_password', 'key')));</code></pre>
<p>This sounds okay but wouldn't it be better whenever we add a user, it should automatically apply <code>encrypt()</code> for the <code>password</code> field or other fields that we want? It would certainly help us save time and keep from repeating code of <code>encrypt()</code> and <code>decrypt()</code> whenever we operated on such field. So to achieve that we extend our classes with this functionality as well:</p>
<pre><code>// wrong code...
class User extends Model extends Encoder  {
    protected $table = 'users';
}</code></pre>
<p>Of course we can't do above. We can't extend a class with multiple classes since in PHP you can only do single inheritance.</p>
<p>So another thought that comes to mind is to extend <code>Model</code>class instead:</p>
<pre><code>abstract class Model extends Encoder {
    // ....
}</code></pre>
<p>And this would certainly work and we would have <code>Encoder</code> functionality available in all our model classes where we can use it the way we need. But think about it. Is it good idea to have Model and Encryption functionality mixed up ? They are totally different things and it doesn't sound like good idea to put encryption logic into your business logic. But then how ? We can use traits !</p>
<p>So let's convert previous <code>Encoder</code> class into a trait:</p>
<pre><code>trait Encoder {
    public static function encrypt($text, $key) {
        // code to encrypt text
    }

    public static function decrypt($text, $key) {
        // code to decrypt text
    } 
}</code></pre>
<p>And to use that trait in some other classes, we need to use it using <code>use Encoder;</code> syntax, so let's add this functionality in our classes:</p>
<pre><code>class User extends Model {
    use Encoder;
    protected $table = 'users';
}

class Message extends Model {
    use Encoder;
    protected $table = 'messages';
}</code></pre>
<p>And now not only our classes inherit functionality from base <code>Model</code> class but also can use the functionality of <code>Encoder</code> trait. We were also able to separate encryption logic from core model logic. So inside our <code>User</code> and <code>Message</code> classes, we can now use <code>$this-&gt;encrypt()</code> or <code>$this-&gt;decrypt()</code> methods as though they were defined in them (Actually that's what PHP does at runtime). We have been able to overcome the shortcoming of single inheritance.</p>
<p>So now when you re-look the definition of traits given at top of this post, it should make better sense. So traits are noting but a way of code-reuse. To learn more about traits and their characteristics, please refer to its  <a href="http://php.net/manual/en/language.oop5.traits.php">documentation</a>.</p>
<blockquote>
<p>Note: One might argue our <code>User</code> and <code>Message</code> classes are also model
logic under the hood but this is just an example to give an idea of
traits. We could have had controllers or other concrete classes too
where we needed common functionality.</p>
</blockquote>]]></description>
<link>https://codeinphp.github.io/post/sharing-functionality-using-traits-in-php</link>
<pubDate>Sun, 26 Apr 2015 01:04:00 +0500</pubDate>
</item>
<item>
<title>Late Static Binding in PHP</title>
<description><![CDATA[<p>Let's jump into an example up front to understand the concept. Let's create two classes parent and child which would tell us the name of the object using <code>getName()</code> method:</p>
<pre><code>class Animal {
    protected $name = 'Animal';

    public function getName() {
        return $this-&gt;name;
    }
}</code></pre>
<p>Let's extend the <code>Animal</code> class so we can use its <code>getName()</code> method without repeating it in child class. We will only need the <code>$name</code> variable in child class to get it's name:</p>
<pre><code>class Cat extends Animal {
    protected $name = 'Cat';
}</code></pre>
<p>Now we expect to get names of each object, let's do so:</p>
<pre><code>$animal = new Animal;
$cat = new Cat;

echo $animal-&gt;getName(); // Animal
echo $cat-&gt;getName(); // Cat</code></pre>
<p>And we successfully get <code>Animal</code> and <code>Cat</code> echoed out. But now let's modify code a bit so that we can use those classes without creating their instances with the help of <code>static</code> keyword (eg global state):</p>
<pre><code>class Animal {
    protected static $name = 'Animal';

    public static function getName() {
        return self::$name;
    }
}

class Cat extends Animal {
    protected static $name = 'Cat';
}

echo Animal::getName(); // Animal
echo Cat::getName(); // Animal</code></pre>
<p>Noticed the problem ? We wanted to see <code>Animal</code> and <code>Cat</code> to be echoed out like previous example but in both cases it said <code>Animal</code> not <code>Cat</code>.</p>
<p>The reason why in previous example things worked the way expected is because we explicitly created new instances of both classes using <code>new</code> keyword and PHP knew which class and method to use. This is not the case in second static example. In the second example, we are using the <code>self</code> keyword which <em>always resolves to current class</em> where it is called. This is reason why the name for the <code>Cat</code> class wasn't echoed out.</p>
<p>So how do we get the name of cat ? Here are few ways.</p>
<p><strong>By Repeating Same Code In Child Class</strong></p>
<pre><code>class Animal {
    protected static $name = 'Animal';

    public static function getName() {
        return self::$name;
    }
}

class Cat extends Animal {
    protected static $name = 'Cat';

    public static function getName() {
        return self::$name;
    }    
}

echo Animal::getName(); // Animal
echo Cat::getName(); // Cat</code></pre>
<p>This works but it defeats the purpose of inheritance. What is the point of extending <code>Animal</code> class when we need to repeat same code in child class ? This isn't ideal.</p>
<p><strong>By Using <code>get_called_class()</code></strong></p>
<pre><code>class Animal {
    protected static $name = 'Animal';

    public static function getName() {
        $class = get_called_class();
        return $class::$name;
    }
}

class Cat extends Animal {
    protected static $name = 'Cat';
}

echo Animal::getName(); // Animal
echo Cat::getName(); // Cat</code></pre>
<p>This is better and works for our purpose.</p>
<p><strong>By Using <code>static</code> keyword</strong></p>
<p>PHP 5.3 introduced the <code>static</code> keyword to help deal with this issue. Before that, <code>get_called_class()</code> was what was used. Let's get the expected result using <code>static</code> keyword:</p>
<pre><code>class Animal {
    protected static $name = 'Animal';

    public static function getName() {
        return static::$name;
    }
}

class Cat extends Animal {
    protected static $name = 'Cat';
}

echo Animal::getName(); // Animal
echo Cat::getName(); // Cat</code></pre>
<p>And this works fine too. These days using <code>static</code> keyword seems to be common practice instead of <code>get_called_class()</code> to deal with this issue though <code>get_called_class()</code> has many other uses too.</p>
<hr />
<p>So in simple words, <strong>late static binding</strong> is something that helps us correctly resolve to <strong>static</strong> classes at run time. So when we use <code>self</code> keyword, PHP checks it at compile time which class to <strong>bind</strong> the method call to but when we use <code>static</code> keyword, PHP would check it <strong>late</strong> eg it would determine which class to use and bind method call to at runtime. Doing it at runtime is what helps PHP determine which class was meant.</p>]]></description>
<link>https://codeinphp.github.io/post/late-static-binding-in-php</link>
<pubDate>Thu, 23 Apr 2015 15:54:00 +0500</pubDate>
</item>
<item>
<title>Closures - PHP vs Javascript</title>
<description><![CDATA[<p>In my previous post <a href="http://codeinphp.github.io/post/exploring-lambda-functions-and-closures-in-php/">Exploring Lambda Functions and Closures in PHP</a>, I gave you example of function that can calculate factorial of given number:</p>
<pre><code>$factorial = function( $n ) use ( &amp;$factorial ) {
    if( $n == 1 ) return 1;
    return $factorial( $n - 1 ) * $n;
};

echo $factorial( 5 ); // 120</code></pre>
<p>In that post I simply said it is important to pass <code>$factorial</code> by <strong>reference</strong> otherwise it won't work. Let's explore why it is so in this post.</p>
<p>Closures are pretty common in Javascript so let's create a simple closure in it and see how it behaves:</p>
<pre><code>var addOne = function(num) {
    return function() { 
        console.log(num++); 
    };
};

var f = addOne(1);

f(); // 1
f(); // 2
f(); // 3</code></pre>
<p>As can be seen, each time we call the function, it increments the number. Let's now convert the same in PHP:</p>
<pre><code>$addOne = function($num) {
    return function() { 
        echo $num++; 
    };
};

$f = $addOne(1);

$f();
$f();
$f();</code></pre>
<p>This would result in error:</p>
<p><code>Notice: Undefined variable: num</code></p>
<p>Why is it so ? Because variable scope is different in PHP and Javascript. In PHP, all variables go in local scope by default unless you explicitly declare them in global scope. However in Javascript all variables go in global scope unless you explicitly declare them in local scope using <code>var</code> keyword. Since we are talking about functions and closures here, we can say that in PHP <em>a variable declared in a function can only be available to that function</em> where it is declared. On the other hand, in Javascript <em>a variable can not only be available to function where it is declared but also to inner functions of that parent function</em>.  Let's see an example:</p>
<pre><code>function test() {
  $variable = 'value';

  return function() {
    echo $variable;
  };
}

$f = test();
$f(); // Notice: Undefined variable: variable</code></pre>
<p>So PHP gave error as inner function didn't had access to outer variable <code>$variable</code>. We could have made this variable available to inner function either by creating closure using <code>use</code> keyword or declaring that variable in global scope. Le't see same example in Javascript:</p>
<pre><code>function test() {
  var variable = 'value';

  return function() {
    console.log(variable);
  };
}

var f = test();
f(); // value</code></pre>
<p>In Javascript though, the inner function was able to get variable from outer scope eg parent function in this example.</p>
<p>This is reason why Javascript inner function shown above didn't give error whereas PHP's did. Therefore to have access to outer variable in PHP, we need to create a closure by using the <code>use</code> keyword. Of course in Javascript, you don't need something like <code>use</code> keyword because as I mentioned in Javascript a variable of a parent function is available to all its inner functions as well. So we need to use the <code>use</code> keyword in PHP due to difference of variable scoping in PHP and Javascript.</p>
<p>So let's fix that error we received earlier in PHP:</p>
<pre><code>$addOne = function($num) {
    return function() use ($num) { 
        echo $num++; 
    };
};

$f = $addOne(1);

$f(); // 1
$f(); // 1
$f(); // 1</code></pre>
<p>Now we have created the closure and error is gone and <code>$num</code> variable is now available to inner function but there is a problem, each time we call the function it says <code>1</code> unlike Javascript example we saw earlier which said <code>1</code>, <code>2</code> and <code>3</code>. That's because unlike Javascript, PHP creates a new local variable inside inner function eg passes it by <code>value</code> not by <code>reference</code>. Conceptually, PHP sees this code like this:</p>
<pre><code>$addOne = function($num) {
    return function() use ($num) { 
        $num = 1;  // so PHP kind of creates a new variable and assigns to 1 each time you call this
        echo $num++; 
    };
};</code></pre>
<p>So to get similar output as in Javascript, we need to pass the variable using <code>reference</code> which can be done by using the <code>&amp;</code> symbol:</p>
<pre><code>$addOne = function($num) {
    return function() use (&amp;$num) { // passed by reference 
        echo $num++; 
    };
};

$f = $addOne(1);

$f();
$f();
$f();</code></pre>
<p>and now we get the output <code>1</code>, <code>2</code>, and <code>3</code>.</p>
<hr />
<p>And that's also reason why you needed to pass variable by <code>reference</code> for the factorial example I had given in my <a href="http://codeinphp.github.io/post/exploring-lambda-functions-and-closures-in-php/">previous post</a>. Hope this post clears the confusion of closures and scoping especially for someone who comes from Javascript to PHP.</p>]]></description>
<link>https://codeinphp.github.io/post/closures-php-vs-javascript</link>
<pubDate>Wed, 22 Apr 2015 14:17:00 +0500</pubDate>
</item>
<item>
<title>Database Migrations in CodeIgniter</title>
<description><![CDATA[<h2>What is Migration ?</h2>
<p>Quoting from CI <a href="https://ellislab.com/codeigniter/user-guide/libraries/migration.html">documentation</a>:</p>
<blockquote>
<p>Migrations are a convenient way for you to alter your database in a
structured and organized manner. You could edit fragments of SQL by
hand but you would then be responsible for telling other developers
that they need to go and run them. You’d also have to keep track of
which changes need to be run against the production machines next time
you deploy.</p>
</blockquote>
<p>Migrations come in extremely handy when you are working with a team of developers. Normally whenever you created a new database table or modified existing one by adding/removing certain fields or even added some data to database, you would tell your fellow developers to run those SQL queries in their machines so that database remains in sync. </p>
<p>This isn't ideal, we needed some way so that:</p>
<ul>
<li>
<p>Framework (CodeIgniter or whatever) <strong>automatically detects and runs</strong> those SQL queries on our behalf without handing over SQL query files to other developers each time we make some change to database</p>
</li>
<li>And keeps <strong>versions of our database changes</strong> similar to versioning of files when we use <strong>git</strong>. This means we can go back and forth easily to specific version of database changes. Something went wrong on production site and you need to revert to specific database change, no problem simply tell CodeIgniter which change to revert to and you are done.</li>
</ul>
<p><strong>That's what migrations do.</strong> </p>
<p>You now see how important and useful migrations are. One of the first frameworks that really shined up with this idea was Laravel and then I saw similar concept in Android applications. CodeIgniter also allows us to setup migrations which is really cool.  </p>
<hr />
<h2>Setting Up Migrations in CodeIgniter</h2>
<p>In order to enable migrations: </p>
<ul>
<li>Open <strong>application/config/migration.php</strong> file and set the value for <code>$config['migration_enabled']</code> from <code>false</code> to <code>true</code>.</li>
<li>Create a folder called <strong>migrations</strong> in <strong>application/config/</strong> folder and that's it.</li>
</ul>
<p>In <strong>migrations</strong> folder, we can create our database changes. Let's say we want to create a new <code>users</code> table. To do so, create a file called <strong>001_add_users.php</strong> in <strong>migrations</strong> folder and paste this code in it:</p>
<pre><code>class Migration_Add_user extends CI_Migration
{
    public function up()
    {
        $this-&gt;dbforge-&gt;add_field(
           array(
              'id' =&gt; array(
                 'type' =&gt; 'INT',
                 'constraint' =&gt; 5,
                 'unsigned' =&gt; true,
                 'auto_increment' =&gt; true
              ),
              'name' =&gt; array(
                 'type' =&gt; 'VARCHAR',
                 'constraint' =&gt; '100',
              ),
              'email' =&gt; array(
                 'type' =&gt; 'TEXT',
                 'null' =&gt; true,
              ),
           )
        );

        $this-&gt;dbforge-&gt;add_key('id', TRUE);
        $this-&gt;dbforge-&gt;create_table('users');
    }

    public function down()
    {
        $this-&gt;dbforge-&gt;drop_table('users');
    }
}</code></pre>
<p>There are few things to notice:</p>
<ul>
<li>We see that this migration class extends <code>CI_Migration</code> class. </li>
<li>It has only two methods <code>up()</code> and <code>down()</code></li>
<li>It uses <code>dbforge</code> object to build up queries in OOP way</li>
<li>The migration files should be prefixed with three digits like <code>001_first_migration.php</code>, <code>002_second_migration.php</code> and so on</li>
</ul>
<p>So that's how a typical migration class should look like. But we are only interested in <code>up()</code> and <code>down()</code> methods. The <code>up()</code> method is called by system whenever you need to update the database and <code>down()</code> method is used to revert that change that was done by the <code>up()</code> method. For example, if in <code>up()</code> method you create a new table then in <code>down()</code> method you should specify code to remove that table. Similarly if in <code>up()</code> method you add a new field to some table then in <code>down()</code> method you should specify code that deletes that field. So both of these methods are opposite to each other. In each migration you should always specify the code for both.</p>
<p>Now that we have created our migration, we need to run it. Let's create a controller called <code>Migrate</code> that will run our migrations:</p>
<pre><code>class migrate extends CI_Controller {
    public function index()
    {
        // load migration library
        $this-&gt;load-&gt;library('migration');

        if ( ! $this-&gt;migration-&gt;current())
        {
            echo 'Error' . $this-&gt;migration-&gt;error_string();
        } else {
            echo 'Migrations ran successfully!'
        }   
    }    
}</code></pre>
<p>Now if you visit your application url at <code>http://yoursite.com/migrate</code> and all goes well, you should success message and the new table <code>users</code> should be created in the database. If you run migration for the first time, you would also notice that a table called <code>migrations</code> should also be created in your database by CodeIgniter. This table can keep track of your database migration changes.</p>
<p>Now refresh page or re-visit <code>http://yoursite.com/migrate</code> and you would notice nothing happens, this time CodeIgniter won't do anything with your migration since it has already been run. To prove it further, delete <code>users</code> table manually from your database and then re-visit <code>http://yoursite.com/migrate</code> page and you will see CodeIgniter didn't create <code>users</code> table again. That's because CodeIgniter knows that it has already run that particular migration. Now if you add some other migrations in <strong>migrations</strong>  folder and then visit migrate URL again, this time CodeIgniter will run your <strong>new</strong> migrations. How does CodeIgniter know which migrations to run ? It keeps track of them <code>migrations</code> table that it creates as well as <code>config['migration_version']</code> setting in application/config/migration.php file. That's how CodeIgniter versions your database changes.</p>
<p>You see how simple and powerful migrations are. Now that you have made changes to database, you don't need to worry how other team members will embrace those changes, all you need to ask them is to visit the migration url and database on their machines will also get those changes!</p>
<p>In the above example, we used <code>$this-&gt;migration-&gt;current()</code> method to go to current migration version that is set in <code>config['migration_version']</code>. There are <a href="https://ellislab.com/codeigniter/user-guide/libraries/migration.html">couple of more methods</a> that allow you to migrate based on most recent version of migration based on file system and one that allows you to go to specific migration version. To lean more about <code>dbforge</code> methods, <a href="http://www.codeigniter.com/user_guide/database/forge.html?highlight=dbforge">check out its documentation</a>.</p>
<p>So if you have never used database migrations before, you should definitely use them because they are awesome!</p>]]></description>
<link>https://codeinphp.github.io/post/database-migrations-in-codeigniter</link>
<pubDate>Tue, 21 Apr 2015 20:50:00 +0500</pubDate>
</item>
<item>
<title>Development Environments in CodeIgniter</title>
<description><![CDATA[<h2>What is Development Environment?</h2>
<p>The environment may be <code>development</code>, <code>staging</code>, <code>production</code> or some other. Each environment can have different set of settings; for example different application configurations, database settings, email settings, logging, error reporting levels and more. By using different environments for your application, you can actually ease things up for yourself when deploying as you won't have to change configurations, database setting and error reporting levels after application is moved to development or production site. Once you setup different development environments, the system would automatically know your application-wide settings to use.</p>
<p>If you have worked with Laravel, you would notice that you can setup different development environments for your application by specifying your current development environment in the <code>.env</code> file. You can actually have different development environments in CodeIgniter as well.</p>
<p>If you open up <strong>index.php</strong> file of CodeIgniter, you would notice it sets <code>development</code> environment as default in a constant <code>ENVIRONMENT</code>:</p>
<p>CodeIgniter 2+:</p>
<pre><code>define('ENVIRONMENT', 'development');</code></pre>
<p>CodeIgniter 3+:</p>
<pre><code>define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');</code></pre>
<p>And later in the very file, CI sets up error reporting based on that environment:</p>
<pre><code>if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;

        case 'production':
            error_reporting(0);
            break;

        default:
            exit('The application environment is not set correctly.');
    }
}</code></pre>
<p>In fact, CI uses <code>ENVIRONMENT</code> constant at quite some places, quoting from its <a href="https://ellislab.com/codeigniter/user-guide/general/environments.html">documentation</a>:</p>
<blockquote>
<p>There are some places in the CodeIgniter system where the <code>ENVIRONMENT</code>
constant is used.</p>
</blockquote>
<hr />
<h2>Setting Different Development Environments</h2>
<p>Let's say we want to have ability to have different development environment for <code>local</code>, <code>development</code> and <code>production</code>. For example, we want to be able to:</p>
<ul>
<li>Have error reporting turned on <code>local</code> and <code>development</code> environments but turned off on <code>production</code></li>
<li>Have logging turned on <code>local</code> and <code>development</code> environments but turned off on <code>production</code></li>
<li>Have different <code>config</code> settings for each of <code>local</code>, <code>development</code> and <code>production</code> environments</li>
<li>Have different <code>database</code> settings for each of <code>local</code>, <code>development</code> and <code>production</code> environments</li>
<li>Have different <code>email</code> settings for each of <code>local</code>, <code>development</code> and <code>production</code> environments</li>
</ul>
<p>According to CI <a href="https://ellislab.com/codeigniter/user-guide/libraries/config.html#environments">documentation</a>, in order to setup different environments, you need to create a folder inside <strong>application/config</strong> folder matching the name of environment. For example, to create <code>development</code> environment, we would create a folder <strong>application/config/development</strong>. </p>
<p>So create three folders named <strong>development</strong>, <strong>local</strong> and <strong>production</strong> inside <strong>application/config</strong> folder. And copy <strong>config.php</strong>, <strong>database.php</strong> and <strong>email.php</strong> from <strong>application/config</strong> to three folders you just created. If email.php doesn't exist, you can create one.</p>
<p>Now each of your <strong>config.php</strong>, <strong>database.php</strong> and <strong>email.php</strong> can have differnt settings. CodeIgniter will <strong>automatically</strong> choose right files to use based on your current environment. For example in <strong>application/config/local/config.php</strong> and <strong>application/config/development/config.php</strong> files, you can enable error reporting and logging using <code>$config['log_threshold']</code> setting by setting it to <code>1</code> but disable error reporting and logging in <code>production</code> environment by setting <code>$config['log_threshold']</code> to <code>0</code> in <strong>application/config/production/config.php</strong> file. Similarly, you can now easily setup different <code>$config['base_url']</code> in each of your environments' config.php file like:
<br><br>
application/config/local/config.php:</p>
<pre><code>$config['base_url'] = 'http://localhost/mysite';</code></pre>
<p>application/config/development/config.php:</p>
<pre><code>$config['base_url'] = 'http://mysite.com/development';</code></pre>
<p>application/config/production/config.php:</p>
<pre><code>$config['base_url'] = 'http://mysite.com';</code></pre>
<hr />
<p>Now when you upload your application, all you have to do is specify which environment you want to use by editing <strong>index.php</strong> file:</p>
<pre><code>define('ENVIRONMENT', 'production'); </code></pre>
<p>If you upload your application to production site, set it to <code>production</code> or if you upload it to development,set it to <code>development</code>.</p>
<p>I am sure you don't want to specify your environment for <code>ENVIRONMENT</code> each time you upload/deploy your application, here is how you can do so:</p>
<pre><code>$local_servers = array('localhost');
$isLocal = in_array($_SERVER['SERVER_NAME'], $local_servers);

if ($isLocal) {
    $env = 'local';
} else {
    // check development word in url
    preg_match('#/development#', $_SERVER['REQUEST_URI'], $isDevelopment);

    $env = $isDevelopment ? 'development' : 'production';
}</code></pre>
<p>And then use <code>$env</code> variable:</p>
<pre><code>define('ENVIRONMENT', $env);</code></pre>]]></description>
<link>https://codeinphp.github.io/post/development-environments-in-codeigniter</link>
<pubDate>Tue, 21 Apr 2015 17:06:00 +0500</pubDate>
</item>
<item>
<title>Controllers for Frontend and Backend in CodeIgniter</title>
<description><![CDATA[<p>I find it very inconvenient when you need to create all <strong>frontend</strong> and <strong>backend</strong> controllers without having any common functionality. I don't like the face that I always have to extend <code>CI_Controller</code> for all my backend and frontend controllers. I need ability to specify which controllers are related to frontend and which ones relate to backend .</p>
<p>So instead of doing this:</p>
<pre><code>class someFrontendController extends CI_Controller {}
class someBackendController extends CI_Controller {}</code></pre>
<p>I should be able to do this:</p>
<pre><code>class someFrontendController extends FrontendController {}
class someBackendController extends BackendController {}</code></pre>
<p>I also need ability to specify <strong>common</strong> controllers that can be <em>applicable to both frontend and backend</em>: </p>
<pre><code>class someCommonController extends CommonController {}</code></pre>
<p>I will explain <strong>benefits</strong> of having such controllers below. But for now, how do we do that ? Well CodeIgniter is very flexible and does allow you to achieve just that.</p>
<h2>Extending CodeIgniter's <code>CI_Controller</code> Class</h2>
<p>In order to have separate controllers for backend, frontend and common controllers, please follow these steps:</p>
<p>1) Make sure that config <code>$config['subclass_prefix']</code> is set to <code>MY_</code> in <strong>application/config.php</strong> file. It should be so by default.</p>
<p>2) Create a file called <strong>MY_Controller.php</strong> in <strong>application/core</strong> folder and paste this code in it:</p>
<pre><code>&lt;?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class CommonController extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
}

class FrontendController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
    }
}

class BackendController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
    }
}</code></pre>
<hr />
<p>Now for all of your controllers that belong to frontend, you would extend <code>FrontendController</code> instead of <code>CI_Controller</code> and for all of your controllers that belong to backend, you would extend <code>BackendController</code> instead of <code>CI_Controller</code> like I mentioned above:</p>
<pre><code>class someFrontendController extends FrontendController {}
class someBackendController extends BackendController {}</code></pre>
<p>And for any controllers that might share common data for frontend and backend, you would extend <code>CommonController</code>:</p>
<pre><code>class someCommonController extends CommonController {}</code></pre>
<h1>What's the Point ?</h1>
<p>You might already have guessed the benefits of having separate controllers but if you haven't  yet, well here they are:</p>
<ul>
<li>You can now easily <strong>distinguish</strong> which controllers belong to backend and which ones belong to frontend</li>
<li>You now have ability to have <strong>common code</strong> for both sides of an application. </li>
</ul>
<p>By <strong>common code</strong>, I mean any functionality that you would want to be shared in all of your controllers. Let's assume that we have created login functionality and user is logged on frontend. Now normally you would write some code in all of your controllers (for authorized pages for example) that would check whether or not user is logged in; if user is not logged in, redirect him back to login page something like:</p>
<pre><code>class MyController extends CI_Controller
{
    public function index() {
        // check if user is logged in
        $this-&gt;checkLoginStatus();

        // more code of controller when user is logged in
    }

    // redirect user to login page if not logged in
    protected function checkLoginStatus() {
        if (! $this-&gt;session-&gt;userdata('is_logged_in')) {
            redirect('login');
        }
    }
}</code></pre>
<p>Now for all of your pages that can be viewed only when user is logged in, you will need to insert <code>checkLoginStatus()</code> function in all of those controllers and then call it <code>index()</code> function. That's not good, it is repeating code. Remember the rules <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">Don't Repeat Yourself</a> (DRY) and <a href="http://en.wikipedia.org/wiki/KISS_principle">Keep It Simple, Stupid!</a> (KISS) :)</p>
<p>Let's KISS it; simply put <code>checkLoginStatus()</code> function code in your <code>FrontendController</code> and now all controllers that extend it will have this login check functionality:</p>
<pre><code>class FrontendController extends CommonController
{
    public function __construct()
    {
        parent::__construct();

        // check if user is logged in
        $this-&gt;checkLoginStatus();
    }

    // redirect user to login page if not logged in
    protected function checkLoginStatus() {
        if (! $this-&gt;session-&gt;userdata('is_logged_in')) {
            redirect('login');
        }
    }    
}</code></pre>
<p>And now you don't need to do anything in your normal frontend controllers. You now get login check functionality out of box. In the similar fashion, you can have some common functionality for all of your backend controllers by putting some code in <code>BackendController</code>. This was just an example for login check but of course you could have some other requirement that you wanted to inject in all of your controllers by using <code>FrontendController</code> or <code>BackendController</code>.</p>
<p>You might ask, you could have done all of this by may be using CI Hooks or may be <a href="http://php.net/manual/en/language.oop5.traits.php">traits</a>, well that's true but I believe having separate controllers gives you more <strong>control</strong> and <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a>.</p>
<p>Similarly, you could put whatever code you want in class for <code>CommonController</code> that would be applicable to <strong>both</strong> frontend and backend. For example you could setup application's overall configuration, upload paths, logos, etc whatever you think should be available site-wide; in all controllers of backend and frontend.</p>
<p>So anything that you put in <code>FrontendController</code> will be available in all controllers of frontend that extend it. Anything that you put in <code>BackendController</code> will be available in all controllers of backend that extend it. Anything that you put in <code>CommonController</code> will be available in all controllers of frontend + backend.</p>
<hr />
<p>And finally there is one more problem I don't like personally. Even though we can now easily find out which controllers belong to frontend or backend, we still have to put all of them in <strong>application/controllers</strong> folder. This doesn't easily tell by looking at file names which controllers belong where unless you open it up and see what it <code>extends</code>. Of course we could use prefix for controller file names like <code>front-foo-controller.php</code> or <code>backend-bar-controller.php</code> but still you have to put them in same folder. It would have been cool if you could have folder structure like this where you can go <strong>any nested level</strong> while having each distinct part of functionality in its own module:</p>
<pre>
+ frontend
   + module-one
      + controllers
          - controllers-one.php
          - controllers-two.php
      + models
          - model-one.php
          - model-two.php
      + views
          - view-one.php
          - view-two.php
   + module-two
   + module-three
+ backend
   + module-one
   + module-two
   + module-three
</pre>
<p>Oh yes you can do that as well with the help of <a href="https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc">HMVC module for CodeIgniter</a> :)</p>
<blockquote>
<p><strong>Note</strong>: HMVC is not just about organizing folders, it is whole concept where you get ability to have one controller call some other
controller. In HMVC, Each model-view-controller triad represents
distinct piece of functionality or mini application which runs
independent from other triads.</p>
</blockquote>
<p>Have fun!</p>]]></description>
<link>https://codeinphp.github.io/post/controllers-for-frontend-and-backend-in-codeigniter</link>
<pubDate>Tue, 21 Apr 2015 15:10:00 +0500</pubDate>
</item>
<item>
<title>CodeIgniter Tip: Time Your Pages</title>
<description><![CDATA[<p>For one of pages in the CodeIgniter application, I needed to find out how much time it takes to load. Pretty obviously first thing that came to mind was to use its built-in <a href="https://ellislab.com/codeigniter/user-guide/libraries/benchmark.html">Benchmarking Class</a>:</p>
<pre><code>$this-&gt;benchmark-&gt;mark('code_start');

// Some code happens here

$this-&gt;benchmark-&gt;mark('code_end');

echo $this-&gt;benchmark-&gt;elapsed_time('code_start', 'code_end');</code></pre>
<p>That's fine as long as you need to benchmark specific points/parts in your code. </p>
<p>But if you need to find out overall time page took to load, you can actually use below variable in your views:</p>
<pre><code>{elapsed_time}</code></pre>
<p>Or simply:</p>
<pre><code>&lt;?php echo $elapsed_time;?&gt;</code></pre>
<p>That variable is automatically created by CodeIgniter.</p>]]></description>
<link>https://codeinphp.github.io/post/codeigniter-tip-time-your-pages</link>
<pubDate>Tue, 21 Apr 2015 13:39:00 +0500</pubDate>
</item>
<item>
<title>Dependency Injection in PHP</title>
<description><![CDATA[<p>This is what Wikipedia has to say about Dependency Injection:</p>
<blockquote>
<p>In software engineering, dependency injection is a software design
pattern that implements inversion of control for software libraries.
Caller delegates to an external framework the control flow of
discovering and importing a service or software module specified or
&quot;injected&quot; by the caller.</p>
</blockquote>
<p>In simple terms, Dependency Injection is a design pattern that helps <em>avoid hard-coded dependencies</em> for some piece of code or software. </p>
<p>The dependencies can be changed at <em>run time as well as compile time</em>. We can use Dependency Injection to write modular, testable and maintainable code:</p>
<ul>
<li><strong>Modular</strong>: The Dependency Injection helps create completely self-sufficient classes or modules</li>
<li><strong>Testable</strong>: It helps write testable code easily eg unit tests for example</li>
<li><strong>Maintainable</strong>: Since each class becomes modular, it becomes easier to manage it</li>
</ul>
<hr />
<h2>The Problem</h2>
<p>We have dependencies almost always in our code. Consider the following procedural example which is pretty common:</p>
<pre><code>function getUsers() {
     global $database;
     return $database-&gt;getAll('users');
}</code></pre>
<p>Here the function <code>getUsers</code> has dependency on the <code>$database</code> variable (tight coupling). It has some of these problems:</p>
<ul>
<li>
<p>The function <code>getUsers</code> needs a <strong>working</strong> connection to <em>some database</em> . Whether there is successful connection to database or not is the fate of <code>getUsers</code> function</p>
</li>
<li>The <code>$database</code> comes from outer scope so chances are it might be overwritten by some other library or code in the same scope in which case function may fail</li>
</ul>
<p>Of course you could have used the <code>try-catch</code> constructs but it still doesn't solve the second problem.</p>
<p>Let's consider another example for a class:</p>
<pre><code>class User 
{
    private $database = null;

    public function __construct() {
        $this-&gt;database = new database('host', 'user', 'pass', 'dbname');
    }

    public function getUsers() {
        return $this-&gt;database-&gt;getAll('users');
    }
}

$user = new User();
$user-&gt;getUsers();</code></pre>
<p>This code again has these problems:</p>
<ul>
<li>
<p>The class <code>User</code> has implicit dependency on the specific <code>database</code>. All dependencies should always be <strong>explicit</strong> not implicit. This defeats <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency inversion principle</a></p>
</li>
<li>
<p>If we wanted to change database credentials, we need to edit the <code>User</code> class which is not good; every class should be completely <strong>modular</strong> or black box. If we need to operate further on it, we should actually use its public properties and methods instead of editing it again and again. This defeats <a href="http://en.wikipedia.org/wiki/Open/closed_principle">Open/closed principle</a></p>
</li>
<li>
<p>Let's assume right now class is using MySQL as database. What if we wanted to use some other type of database ? You will have to modify it.</p>
</li>
<li>
<p>The <code>User</code> class does not necessarily need to know about database connection, it should be confined to its own functionality only. So writing database connection code in <code>User</code> class doesn't make it modular. This defeats the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single responsibility principle</a>. Think of this analogy: A cat knows how to <code>meow</code> and a dog knows how to <code>woof</code>; you cannot mix them or expect dog to say <code>meow</code>. Just like real world, each object of a class should be responsible for its own specific task.</p>
</li>
<li>It would become harder to write unit tests for the <code>User</code> class because we are instantiating the database class inside its constructor so it would be impossible to write unit tests for the <code>User</code> class without also testing the database class.</li>
</ul>
<h2>Enter Dependency Injection!</h2>
<p>Let's see how we can easily take care of above issues by using Dependency Injection. The Dependency Injection is nothing but <strong>injecting a dependency explicitly</strong>. Let's re-write above class:</p>
<pre><code>class User 
{
    private $database = null;

    public function __construct(Database $database) {
        $this-&gt;database = $database;
    }

    public function getUsers() {
        return $this-&gt;database-&gt;getAll('users');
    }
}

$database = new Database('host', 'user', 'pass', 'dbname');
$user = new User($database);
$user-&gt;getUsers();</code></pre>
<p>And there you have much better code, thanks to Dependency Injection principle. Notice that instead of hard-coding database dependency:</p>
<pre><code>$this-&gt;database = new database('host', 'user', 'pass', 'dbname');</code></pre>
<p>We are now injecting it into the constructor, that's it:</p>
<pre><code>public function __construct(Database $database)</code></pre>
<p>Notice also how we are passing database instance now:</p>
<pre><code>$database = new Database('host', 'user', 'pass', 'dbname');
$user = new User($database);
$user-&gt;getUsers();</code></pre>
<p>It follows <a href="http://en.wikipedia.org/wiki/Hollywood_Principle">Hollywood Principle</a>, which states: <strong>&quot;Don’t call us, we’ll call you.&quot;</strong></p>
<p>Let's see if this explicit dependency injection now solves problems we mentioned above.</p>
<hr />
<blockquote>
<p>The class User has implicit dependency on the specific database
. All dependencies should always be explicit not implicit.
This defeats Dependency inversion principle</p>
</blockquote>
<p>We have already made database dependency explicit by requiring it into the constructor of the <code>User</code> class:</p>
<pre><code>public function __construct(Database $database)</code></pre>
<p>Here we are taking advantage of <strong>type hinting</strong> by specifying type of object we are expecting which is <code>Database</code> although it wasn't necessary but it is always a good idea to type hint when you can.</p>
<blockquote>
<p>If we wanted to change database credentials, we need to edit the User
class which is not good; every class should be completely modular or
black box. If we need to operate further on it, we should actually use
its public properties and methods instead of editing it again and
again. This defeats Open/closed principle</p>
</blockquote>
<p>The <code>User</code> class now does not need to worry about how database is connected. All it expects is <code>Database</code> instance. We no more need to edit <code>User</code> class for it's dependency, we have just provided it with what it needed.</p>
<blockquote>
<p>Let's assume right now class is using MySQL as database. What if we
wanted to use some other type of database ? You will have to modify
it.</p>
</blockquote>
<p>Again, the <code>User</code> class doesn't need to know which type of database is used. For the <code>Database</code>, we could now create different adapters for different types of database and pass to <code>User</code> class. For example, we could create an <code>interface</code> that would enforce common methods for all different types of database classes that must be implement by them. For our example, we pretend that interface would enforce to have a <code>getUser()</code> method requirement in different types of database classes.</p>
<blockquote>
<p>The User class does not necessarily need to know about database
connection, it should be confined to its own functionality only. So
writing database connection code in User class doesn't make it
modular. This defeats the Single responsibility principle.</p>
</blockquote>
<p>Of course <code>User</code> class now doesn't know how database was connected. It just needs a valid connected <code>Database</code> instance.</p>
<blockquote>
<p>It would become harder to write unit tests for the User class because
we are instantiating the database class inside its constructor so it
would be impossible to write unit tests for the User class without
also testing the database class.</p>
</blockquote>
<p>If you have wrote unit tests, you know now it will be a breeze to write tests for the <code>User</code> class using something like <a href="https://github.com/padraic/mockery">Mockery</a> or similar to create mock object for the <code>Database</code>.</p>
<hr />
<h2>Different Ways of Injecting Dependencies</h2>
<p>Now that we have seen how useful Dependency Injection is, let's see different ways of injecting dependencies. There are three ways you can inject dependencies:</p>
<ul>
<li>Constructor Injection</li>
<li>Setter Injection</li>
<li>Interface Injection</li>
</ul>
<p><strong>Constructor Injection</strong></p>
<p>We have already seen example of <strong>Constructor Injection</strong> in above example. Constructor injection is useful when:</p>
<ul>
<li>
<p>A dependency is <strong>required</strong> and class can't work without it. By using constructor injection. we make sure all its required dependencies are passed.</p>
</li>
<li>Since constructor is called only at the time of instantiating a class, we can make sure that its dependencies cant be changed during the life time of the object.</li>
</ul>
<p>Constructor injection suffer from one problem though:</p>
<ul>
<li>Since constructor has dependencies, it becomes rather difficult to extend/override it in child classes.</li>
</ul>
<p><strong>Setter Injection</strong></p>
<p>Unlike Constructor injection which makes it <strong>required</strong> to have its dependencies passed, setter injection can be used to have <strong>optional dependencies</strong>. Let's pretend that our <code>User</code> class doesn't require <code>Database</code> instance but uses optionally for certain tasks. In this case, you would use a setter method to inject the <code>Database</code> into the <code>User</code> class something like:</p>
<pre><code>class User 
{
    private $database = null;

    public function setDatabase(Database $database) {
        $this-&gt;database = $database;
    }

    public function getUsers() {
        return $this-&gt;database-&gt;getAll('users');
    }
}

$database = new Database('host', 'user', 'pass', 'dbname');
$user = new User();
$user-&gt;setDatabase($database);
$user-&gt;getUsers();</code></pre>
<p>As you can see, here we have used <code>setDatabase()</code> setter function to inject <code>Database</code> dependency into the <code>User</code> class. If we needed some other dependency, we could have created one more setter method and injected in the similar fashion.</p>
<p>So Setter Injection is useful when:</p>
<ul>
<li>A class needs optional dependencies so it can set itself up with default values or add additional functionality it needs.</li>
</ul>
<blockquote>
<p>Notice that you could also inject dependency via <strong>public property</strong>
for a class. So instead of using setter function
<code>$user-&gt;setDatabase($database);</code>, you could also do <code>$user-&gt;database = new Database(...);</code></p>
</blockquote>
<p><strong>Interface Injection</strong></p>
<p>In this type of injection, an interface enforces the dependencies for any classes that implement it, for example:</p>
<pre><code>interface someInterface {
    function getUsers(Database $database);
}</code></pre>
<p>Now any class that needs to implement <code>someInterface</code> must provide <code>Database</code> dependency in their <code>getUsers()</code> methods.</p>
<hr />
<h2>The Problem Again</h2>
<p>So for we have seen very contrived example of injecting dependency into a simple class but in real world applications, a class might have many dependencies. It isn't all that easy to manage all those dependencies because you need to KNOW which dependencies are required by a certain class and HOW they need to be instantiated. Let's take example of setter injection:</p>
<pre><code>class User 
{
    private $database = null;

    public function setDatabase(Database $database) {
        $this-&gt;database = $database;
    }

    public function getUsers() {
        return $this-&gt;database-&gt;getAll('users');
    }
}</code></pre>
<p>Since dependencies in this case are optional, we could have mistakenly written this code to get users:</p>
<pre><code>$user = new User();
$user-&gt;getUsers();</code></pre>
<p>Since we didn't know <code>getUsers()</code> method is actually dependent on <code>Database</code> class, this would have given error. You could have found that out only by going to code of <code>User</code> class and then realizing there is <code>setDatabase()</code> method that must be called before using the <code>getUsers()</code> method. Or let's assume further that before using database, we needed to set some type of configuration for the <code>User</code> class like:</p>
<pre><code>$user = new User();
$user-&gt;setConfig($configArray);</code></pre>
<p>Then again we needed to remember specific order of method calls:</p>
<pre><code>$user = new User();
$user-&gt;setConfig($configArray);
$user-&gt;setDatabase($database);</code></pre>
<p>So you must remember order of method calls, you can't use database if you don't setup configuration first, so you can't do:</p>
<pre><code>$user = new User();
$user-&gt;setDatabase($database);
$user-&gt;setConfig($configArray);</code></pre>
<p>This is example for setter injection but even with constructor injection if there are many dependencies, it becomes harder to manage all of those manually and you could easily and mistakenly create more than one instances of dependencies throughout your code which would result in high memory usage.</p>
<p>You might wonder dependency injection sounded like good thing to have but these problems are not worth it. Well that's not true because there is solution to all of these problems discussed next :)</p>
<h2>Solution - Dependency Injection Container</h2>
<p>Of course it would be difficult to manage dependencies manually; this is why you need a Dependency Injection Container. A Dependency Injection Container is something that handles dependencies for your class(es) automatically. If you have worked with Laravel or Symfony, you know that their components have dependencies on on other classes. How do they manage all of those dependencies ? Yes they use some sort of Dependency Injection Container.</p>
<p>There are <a href="http://www.sitepoint.com/php-dependency-injection-container-performance-benchmarks/">quite some dependency injection containers out there for PHP</a> that can be used for this purpose or you can also write your own. Each container might have bit of different syntax but they perform the same thing under the hood.</p>
<hr />
<p>So in conclusion, you must always remove hard-coded dependencies from your code and inject them using Dependency Injection instead for its benefits and then have all the injected dependencies managed automatically for you by using some dependency injection container.</p>]]></description>
<link>https://codeinphp.github.io/post/dependency-injection-in-php</link>
<pubDate>Sun, 19 Apr 2015 21:44:00 +0500</pubDate>
</item>
<item>
<title>Visual Query - A Basic MySQL Query Builder App</title>
<description><![CDATA[<p>The client I am working with is <em>somewhat</em> technical and he wanted the ability to create his own reporting out of database. He isn't all that expert in knowing SQL so in order to help him I built <strong>Visual Query</strong> app to help him <strong>build his SQL queries visually</strong> through a provided interface.</p>
<p>Visual Query is basic MySQL query builder and database browser app that has these basic features:</p>
<ul>
<li>Ability to choose different databases</li>
<li>Ability to export result set to CSV and Excel</li>
<li>Custom queries option</li>
<li>Visual Query builder</li>
<li>Query log, search facility, pagination, etc</li>
</ul>
<p>Here is how it looks:</p>
<p><img src="https://codeinphp.github.io/images/1429438678553380d670675.png" alt="enter image description here" /></p>
<hr />
<p>One can also write custom queries with syntax highlighting support as well as code prediction support:</p>
<p><img src="https://codeinphp.github.io/images/1429438683553380db1db48.png" alt="enter image description here" /></p>
<hr />
<p>And here is the query builder interface:</p>
<p><img src="https://codeinphp.github.io/images/1429438687553380df677ee.png" alt="enter image description here" /></p>
<hr />
<h2>How to Use</h2>
<p>First of all, download it from <a href="https://github.com/sarfraznawaz2005/VisualQuery">its repository</a>. Once downloaded, edit the <code>config.php</code> file with database details and users login information:</p>
<pre><code>// edit database settings
$config['database_host'] = 'localhost';
$config['database_user'] = 'root';
$config['database_password'] = '';
$config['database_dbname'] = 'mydb';

//////////////////////////////////////////////
// user details who can login - You can also specify more than one user
//////////////////////////////////////////////

// user 1
$config['username'][] = 'admin';
$config['password'][] = 'admin';

// user 2
$config['username'][] = 'admin2';
$config['password'][] = 'admin2';</code></pre>]]></description>
<link>https://codeinphp.github.io/post/visual-query-a-basic-mysql-query-builder-app</link>
<pubDate>Sun, 19 Apr 2015 12:31:00 +0500</pubDate>
</item>
<item>
<title>Extending DataMapper for CodeIgniter</title>
<description><![CDATA[<p>For one of my projects I was using CodeIgniter framework with goodies like <a href="http://datamapper.wanwizard.eu/">DataMapper</a> (by wanwizard.eu), <a href="https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc">HMVC Module</a>, <a href="http://github.com/EllisLab/CodeIgniter/wiki/View-Object-PHP5">View Objects</a> and more. Everything was smooth and sound until client requested that some of database tables must be encrypted. I was already encrypting sensitive information like passwords, etc but client wanted encryption for more tables such that:</p>
<ul>
<li>One-way hashing, once data is encrypted, it can't be decrypted,  we chose <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">AES</a> (Advanced Encryption Standard)</li>
<li>For same piece of text, hashing should be able to generate different encrypted text always so no two same text should sound like similar</li>
<li>Code should know whether provided piece of text is already encrypted or not</li>
</ul>
<p>I created the encryption class and did some trickery so that it always gave <em>different encryption text</em> for the <em>same string</em>. And also used some kind of prefix information that would later let the code know whether or not something is already encrypted.</p>
<p>The real problem for me was that by the time project had turned into huge codebase, it would have taken ages to go and modify code everywhere so that new requirement of encryption is applied everywhere. I was using <a href="http://datamapper.wanwizard.eu/">DataMapper</a> library everywhere to interact with database and model classes looked like this:</p>
<pre><code>class Api_client extends DataMapper
{
    # object properties
    public $id;
    public $appid;
    public $apikey;
    public $request_uri;

    # relations
    public $has_one = array('client');

    # validation
    public $validation = array(
        'appid' =&gt; array(
            'label' =&gt; 'App ID',
            'rules' =&gt; array('required', 'trim')
        ),
        'apikey' =&gt; array(
            'label' =&gt; 'API Key',
            'rules' =&gt; array('required', 'trim')
        ),
        'request_uri' =&gt; array(
            'label' =&gt; 'Request URI',
            'rules' =&gt; array('required', 'trim')
        )
    );

    # Default to ordering by id
    public $default_order_by = array('id' =&gt; 'desc');

    # Optional - useful if a record is to be retrieved by ID eg $user = new User(1);
    public function __construct($id = null)
    {
        parent::__construct($id);
    }

    # Optional - post model initialisation code
    public function post_model_init($from_cache = false)
    {
    }
}</code></pre>
<p>We can see that each model class extends the data mapper:</p>
<pre><code>class Api_client extends DataMapper</code></pre>
<p>This is what was a clue to me. So in order to avoid modifying lots of code in whole codebase, I knew I can only extend this data mapper and inject my functionality the way I needed.</p>
<p>I actually needed the ability to:</p>
<ul>
<li>automatically encrypt given fields in some table when saving them to database</li>
<li>automatically getting the right value when reading back from database</li>
</ul>
<p>By that I mean, instead of going everywhere in codebase and modifying code to encrypt certain fields like this:</p>
<pre><code>$apiClient = new Api_client();
$apiClient-&gt;appid = Encode($appId);     // encrypt this field value
$apiClient-&gt;apikey = Encode($apikey);  // encrypt this field value
$apiClient-&gt;request_uri = $request_uri;
$apiClient-&gt;save(); // save to db</code></pre>
<p>I simply wanted to leave current code as is without modifying it:</p>
<pre><code>$apiClient = new Api_client();
$apiClient-&gt;appid = $appId;
$apiClient-&gt;apikey = $apikey;
$apiClient-&gt;request_uri = $request_uri;
$apiClient-&gt;save(); // save to db</code></pre>
<p>In this case, I wanted data mapper to <strong>automatically</strong> encrypt the <code>appid</code> and <code>apikey</code> values for me. Now imagine I had this code placed in quite some files, it would have been time-consuming process to modify and add <code>Encode()</code> function calls manually everywhere.</p>
<p>In order to do that, I simply told data mapper which fields need to be encrypted:</p>
<pre><code>class Api_client extends DataMapper
{
    ////////////////////

    // for encryption fields
    private $encryptFields = array(
       'appid',
       'apikey',
    );    
}</code></pre>
<p>Now if you look at the code of data mapper, you would see it uses <code>_to_object()</code> function to map fields and <code>save()</code> function to save the info to database. So I tapped into these in my child classes and modified them a bit so that <code>$encryptFields</code> are auto-magically encrypted on my behalf. Since we are extending data mapper (<code>class Api_client extends DataMapper</code>), I modified it like this to do the encryption for me:</p>
<pre><code>class Api_client extends DataMapper
{
    # object properties
    public $id;
    public $appid;
    public $apikey;
    public $request_uri;

    # relations
    public $has_one = array('client');

    # validation
    public $validation = array(
    'appid' =&gt; array('label' =&gt; 'App ID', 'rules' =&gt; array('required', 'trim')), 
    'apikey' =&gt; array('label' =&gt; 'API Key', 'rules' =&gt; array('required', 'trim')), 
    'request_uri' =&gt; array('label' =&gt; 'Request URI', 'rules' =&gt; array('required', 'trim'))
    );

    // for encryption fields
    private $encryptFields = array('appid', 'apikey');

    # Default to ordering by id
    public $default_order_by = array('id' =&gt; 'desc');

    # Optional - useful if a record is to be retrieved by ID eg $user = new User(1);
    public function __construct($id = null)
    {
        parent::__construct($id);
    }

    # Optional - post model initialisation code
    public function post_model_init($from_cache = false)
    {
    }

    // extending date modal here //
    public function _to_object($item, $row)
    {
        // Populate this object with values from first record
        foreach ($row as $key =&gt; $value) {
            if ($this-&gt;isEncryptedField($key)) {
                $item-&gt;{$key} = decodeField($value);
            } else {
                $item-&gt;{$key} = $value;
            }
        }

        foreach ($this-&gt;fields as $field) {
            if (!isset($row-&gt;{$field})) {
                $item-&gt;{$field} = null;
            }
        }

        // Force IDs to integers
        foreach ($this-&gt;_field_tracking['intval'] as $field) {
            if (isset($item-&gt;{$field})) {
                $item-&gt;{$field} = intval($item-&gt;{$field});
            }
        }

        if (!empty($this-&gt;_field_tracking['get_rules'])) {
            $item-&gt;_run_get_rules();
        }

        $item-&gt;_refresh_stored_values();

        if ($this-&gt;_instantiations) {
            foreach ($this-&gt;_instantiations as $related_field =&gt; $field_map) {
                // convert fields to a 'row' object
                $row = new stdClass();
                foreach ($field_map as $item_field =&gt; $c_field) {
                    $row-&gt;{$c_field} = $item-&gt;{$item_field};
                }

                // get the related item
                $c =&amp; $item-&gt;_get_without_auto_populating($related_field);
                // set the values
                $c-&gt;_to_object($c, $row);

                // also set up the -&gt;all array
                $c-&gt;all    = array();
                $c-&gt;all[0] = $c-&gt;get_clone();
            }
        }
    }

    public function save($object = '', $related_field = '')
    {
        // Temporarily store the success/failure
        $result = array();

        // Validate this objects properties
        $this-&gt;validate($object, $related_field);

        // If validation passed
        if ($this-&gt;valid) {

            // Begin auto transaction
            $this-&gt;_auto_trans_begin();

            $trans_complete_label = array();

            // Get current timestamp
            $timestamp = $this-&gt;_get_generated_timestamp();

            // Check if object has a 'created' field, and it is not already set
            if (in_array($this-&gt;created_field, $this-&gt;fields) &amp;&amp; empty($this-&gt;{$this-&gt;created_field})) {
                $this-&gt;{$this-&gt;created_field} = $timestamp;
            }

            // SmartSave: if there are objects being saved, and they are stored
            // as in-table foreign keys, we can save them at this step.
            if (!empty($object)) {
                if (!is_array($object)) {
                    $object = array(
                        $object
                    );
                }

                $this-&gt;_save_itfk($object, $related_field);
            }

            // Convert this object to array
            $data = $this-&gt;_to_array();
            $data = $this-&gt;changeWithEncrypted($data);
            //pretty_print($data);

            if (!empty($data)) {
                if (!$this-&gt;_force_save_as_new &amp;&amp; !empty($data['id'])) {
                    // Prepare data to send only changed fields
                    foreach ($data as $field =&gt; $value) {
                        // Unset field from data if it hasn't been changed
                        if ($this-&gt;{$field} === $this-&gt;stored-&gt;{$field}) {
                            unset($data[$field]);
                        }
                    }

                    // if there are changes, check if we need to update the update timestamp
                    if (count($data) &amp;&amp; in_array($this-&gt;updated_field, $this-&gt;fields) &amp;&amp; !isset($data[$this-&gt;updated_field])) {
                        // update it now
                        $data[$this-&gt;updated_field] = $this-&gt;{$this-&gt;updated_field} = $timestamp;
                    }

                    // Only go ahead with save if there is still data
                    if (!empty($data)) {
                        // Update existing record
                        $this-&gt;db-&gt;where('id', $this-&gt;id);
                        $this-&gt;db-&gt;update($this-&gt;table, $data);

                        $trans_complete_label[] = 'update';
                    }

                    // Reset validated
                    $this-&gt;_validated = false;

                    $result[] = true;
                } else {
                    // Prepare data to send only populated fields
                    foreach ($data as $field =&gt; $value) {
                        // Unset field from data
                        if (!isset($value)) {
                            unset($data[$field]);
                        }
                    }

                    // Create new record
                    $this-&gt;db-&gt;insert($this-&gt;table, $data);

                    if (!$this-&gt;_force_save_as_new) {
                        // Assign new ID
                        $this-&gt;id = $this-&gt;db-&gt;insert_id();
                    }

                    $trans_complete_label[] = 'insert';

                    // Reset validated
                    $this-&gt;_validated = false;

                    $result[] = true;
                }
            }

            $this-&gt;_refresh_stored_values();

            // Check if a relationship is being saved
            if (!empty($object)) {
                // save recursively
                $this-&gt;_save_related_recursive($object, $related_field);

                $trans_complete_label[] = 'relationships';
            }

            if (!empty($trans_complete_label)) {
                $trans_complete_label = 'save (' . implode(', ', $trans_complete_label) . ')';
            } else {
                $trans_complete_label = '-nothing done-';
            }

            $this-&gt;_auto_trans_complete($trans_complete_label);

        }

        $this-&gt;_force_save_as_new = false;

        // If no failure was recorded, return TRUE
        return (!empty($result) &amp;&amp; !in_array(false, $result));
    }

    private function isEncryptedField($key)
    {
        if (false !== in_array($key, $this-&gt;encryptFields)) {
            return true;
        }

        return false;
    }

    private function changeWithEncrypted(array $array)
    {
        foreach ($array as $key =&gt; $value) {
            if ($this-&gt;isEncryptedField($key)) {
                if ($value !== '') {
                    $array[$key] = encodeField($value);
                } else {
                    $array[$key] = $value;
                }
            }
        }

        return $array;
    }

    private function _get_generated_timestamp()
    {
        // Get current timestamp
        $timestamp = ($this-&gt;local_time) ? date($this-&gt;timestamp_format) : gmdate($this-&gt;timestamp_format);

        // Check if unix timestamp
        return ($this-&gt;unix_timestamp) ? strtotime($timestamp) : $timestamp;
    }

}</code></pre>
<p>In above class, most of the code remains same for <code>_to_object()</code> and <code>save()</code> functions as in original data mapper class but I have modified few places so that I can put encryption for needed fields.</p>
<p>So in conclusion, we learned how we tapped onto the data mapper class and extended it for our needs of auto-encryption of told fields. If you happen to have similar requirement or you wanted to inject your own functionality to the data mapper, you can do that through the use of <code>_to_object()</code>  and <code>save()</code> functions of data mapper.</p>]]></description>
<link>https://codeinphp.github.io/post/extending-datamapper-for-codeigniter</link>
<pubDate>Sun, 19 Apr 2015 11:35:00 +0500</pubDate>
</item>
<item>
<title>JavaScript Best Practices</title>
<description><![CDATA[<p>JavaScript is not only amazing language but also very tricky language. To make correct use of it, you need to follow some best practices to avoid any problems that might come about otherwise. I share some of the best practices you really should be following when writing JavaScript code. Of course this is not an exhaustive list but at the most fundamental level, every programmer should know and adhere to it.</p>
<h2>1 -NEVER FORGET <code>VAR</code> KEYWORD</h2>
<p>Most of the developers know about this but yet I wanted to mention this because it may not be clear to some or newbies or people having other programming language background that come to JavaScript.</p>
<p>Consider the following piece of code:</p>
<pre><code>function myFunc(){
    var firstName = 'sarfraz';
    lastName = 'ahmed';
}</code></pre>
<p>It should be noted that in JS, variables have function-level scope which means a variable declared inside a function can not be accessed outside of it. So let’s test above two variables:</p>
<pre><code>myFunc();
console.log(lastName); // ahmed
console.log(firstName); // undefined</code></pre>
<p>As you will notice, we are still able to access <code>lastName</code> variable. The reason is that it does not have function-level scope because we forgot to put var keyword before it unlike <code>firstName</code> variable. Hence, <code>lastName</code> variable went into <strong>global</strong> scope and became part of <code>window</code> (while inside browser) object eg <code>window.lastName</code> will output the last name too.</p>
<p>It is therefore always required to put <code>var</code> keyword before variables so that they do not become part of global scope. It has following benefits:</p>
<ul>
<li>You save the memory and improve performance</li>
<li>You don’t pollute the global scope</li>
<li>You mistakenly don’t overwrite a global variable that might have the same variable name</li>
</ul>
<p>This is a very important concept and JS developers have always been finding solutions to avoid this problem. One of the most popular solution is <a href="http://chrisiona.com/learning-modern-javascript/the-singleton-pattern/">Singleton</a> or <a href="http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth">Module Pattern</a> you should check out. By the way, if you want to see other patterns also, take a look at:</p>
<p><a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/">Essential JavaScript Design Patterns For Beginners</a></p>
<h2>2 – DECLARE VARIABLES ON TOP</h2>
<p>Another thing that should be followed is that variables should be declared on top of each function because of what is known as <strong>JavaScript Hoisting</strong>. Here is an example:</p>
<pre><code>var name = 'sarfraz';

(function(){
console.log(name); // undefined
     var name = 'nawaz';
     console.log(name); // nawaz
})();</code></pre>
<p>Notice that even though <code>name</code> variable is outside the scope of function but on the very first line it gives back <code>undefined</code> rather than actual name. The reason for this is that interpreter hoists or moves variables on top of the function, here is how interpreter sees or re-arranges it:</p>
<pre><code>var name = 'sarfraz';

(function(){
     var name;
     console.log(name); // undefined
     name = 'nawaz';
     console.log(name); // nawaz
})();</code></pre>
<p>As can be seen, <code>name</code> variable has been hoisted to top and declared there and also <code>var</code> keyword has been stripped from it where we assigned the value of <code>nawaz</code>.</p>
<p>The same is issue is not only with variables but also <strong>function declarations</strong> but NOT with <strong>function expressions</strong>. You can learn more about the difference between function declaration and function expression here:</p>
<p><a href="http://kangax.github.com/nfe/">Named Functions Demystified</a></p>
<p>The solution to this problem is to always declare <strong>variables and function declarations</strong> on top of container function:</p>
<pre><code>function myFunc(){
     var foo;
     var bar;
     var baz;

     // do something foo, bar, baz
}</code></pre>
<p>The preferred and recommended syntax though that you must follow is to declare all variables in one go by separating them with a comma:</p>
<pre><code>function myFunc(){
     var foo, bar, baz;

     // do something foo, bar, baz
}</code></pre>
<h2>3 – INITIALIZING MULTIPLE VARIABLES</h2>
<p>Declaring variables on top is good practice but not <em>multiple initialization</em>. Consider:</p>
<pre><code>function myFunc(){
    var lang = encoding = 'en';
}</code></pre>
<p>This is a very common mistake even amongst experienced JS developers where they think they have quickly assigned two variables same scope and same value. Though value for both <code>lang</code> and <code>encoding</code> variable is some but not the scope. Try it out:</p>
<pre><code>myFunc();
console.log(encoding); // en
console.log(lang); // undefined</code></pre>
<p>Here again, variable <code>encoding</code> has gone into global scope. Since <code>var</code> keyword is only appears before <code>lang</code> variable, that is the one which gets correct functional scope. In short, you should avoid that shorthand initialization unfortunately.</p>
<h2>4 – STARTING CURLY BRACE ON THE SAME LINE</h2>
<p>Consider the following code block where starting curly brace <code>{</code> is on a new line, this works fine in most situations:</p>
<pre><code>function myFunc()
{
    // some code
}</code></pre>
<p>However, same convention will not yield expected results if you happen to write:</p>
<pre><code>function myFunc()
{
     return
     {
         name: 'sarfraz'
     };
}

var f = myFunc();
console.log(f);</code></pre>
<p>The result will be <code>undefined</code> because behind the scenes, interpreter puts a semicolon <code>;</code> after the <code>return</code> keyword making it:</p>
<pre><code>function myFunc()
{
     return; // &lt;----------------
     {
         name: 'sarfraz'
     };
}</code></pre>
<p>To remedy such hard-to-debug issues, it is good practice to always put starting curly brace on the <strong>same line</strong>, this would work fine though:</p>
<pre><code>function myFunc() {
     return {
         name: 'sarfraz'
     };
}

var f = myFunc();
console.log(f.name); // sarfraz</code></pre>
<p>And that’s a reason why <a href="http://www.crockford.com/">Douglas Crockford</a> in his book “<a href="http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742">JavaScript: The Good Parts</a>“, advocates this syntax for JS:</p>
<pre><code>function () {
     // some code
}

if (expression) {
     // do something
}</code></pre>
<p>Go ahead and check out <a href="http://javascript.crockford.com/code.html">JavaScript Coding Style</a> to learn more as well as naming conventions.</p>
<p>Notice that it is not the <code>return</code> keyword affected by automatic semi-colon insertion but all these too:</p>
<ul>
<li><strong>var</strong> statement</li>
<li><strong>empty</strong> statement</li>
<li><strong>expression</strong> statement</li>
<li><strong>do-while</strong> statement</li>
<li><strong>continue</strong> statement</li>
<li><strong>break</strong> statement</li>
<li><strong>throw</strong> statement</li>
</ul>
<p>Experienced JavaScript developers know pretty well about JavaScript’s <em>automatic semi-colon insertion problem</em> and avoid it. The benefit of above coding style however is that you avoid this problem without knowing that this problem exists just by following that coding style.</p>
<h2>5 – USE ARRAY LITERAL INSTEAD OF NEW ARRAY()</h2>
<p>There are two ways you can create arrays in JS:</p>
<pre><code>var arr1 = new Array(); // array constructor
var arr2 = []; // array literal</code></pre>
<p>Though both serve the purpose of creating arrays but there is important difference between the two.</p>
<p>In JS, even an array is an object. With first constructor method above, you are telling interpreter to call constructor of the <code>Array</code> and generate an object. The interpreter looks up into the execution context to find the constructor and once found, it calls it and creates the <code>Array</code> object. It seems that it has performance hit too as compared to latter array literal method. With the array literal method, interpreter just creates the array on run-time with no extra processing done.</p>
<p>Other than that, Array constructor is mis-guiding the way it handles its parameters. Consider:</p>
<pre><code>console.log(new Array(5)); // [,,,,]
console.log(new Array('5')); // ["5"]</code></pre>
<p>When one argument is passed to Array and that happens to be a number, a new array is returned with its length property equal to that number passed. The important thing to note here is that Array will be initialized from what number you specified to it, for example:</p>
<pre><code>// Array constructor
var arr = new Array(2);
console.log(arr.length); // 2
console.log(arr[0]); // undefined

// Array literal
var arr = [2];
console.log(arr.length); // 1
console.log(arr[0]); // 2</code></pre>
<p>So the conclusion is to always use array literal notation rather than Array constructor.</p>
<h2>6 – USE PROTOTYPE TO SHARE ACROSS</h2>
<p>The concept of prototypes or prototypal inheritance is rather confusing. I have seen people especially inexperienced JS developers adding class members to parent function which needs to be shared across child classes. Consider the following code:</p>
<pre><code>function Person(name){
    this.name = name;
}</code></pre>
<p>Now let’s assume we want to have child classes the ability to display the names some how, one of doing it is putting method directly inside <code>Person</code> class:</p>
<pre><code>function Person(name){
     this.name = name;

     this.display = function(){
         alert(this.name);
     }
}</code></pre>
<p>Other way is to use <code>prototype</code>:</p>
<pre><code>function Person(name){
     this.name = name;
}

Person.prototype.display = function(){
     alert(this.name);
}</code></pre>
<p>With both ways, all child classes will be able to use the display method but there is important difference between the two. When you attach any methods or properties via <code>this</code> (first way above) to a class then all instances of inheriting child classes will also have these properties or methods within them or their signature. On the other hand, when you use <code>prototype</code> to add members (properties and methods) to parent class, children classes will still inherit all members but it won’t be present inside their own functionality or signature, rather they will be borrowing that functionality from their parent class thereby saving memory. For this reason, later approach seems good to follow in most situations.</p>
<h2>7 – PUT COMMA BEFORE PROPERTIES</h2>
<p>When working with objects or arrays, it is always a good idea to put a comma before the variable or object property eg:</p>
<pre><code>// jQuery - create a new div with some css
$('&lt;div&gt;').attr({
   "id"       : "myId"
 , "class" : "myClass"
 , "class" : "myClass"
 , "color" : "green"
 , "fontWeight" : "bold"
});</code></pre>
<p>In this way, we never add an extra comma or forget one from the last property. The reason why this is good practice is that, in IE, with extra comma at the last property, we do not get expected results sometimes (<strong>ExtJS</strong> developers must have learned this). I do the same with multiple variable declarations or arguments of function. It also makes the code look pretty too as far as I see it.</p>
<h2>8 – DON’T MIX JS AND HTML</h2>
<p>One of the most important best practices is to always <em>separate JS code from HTML</em> and go <a href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript">unobtrusive</a>. One would often see code like this:</p>
<pre><code>&lt;a href="#" onclick="doSomething()"&gt;Some Action&lt;/a&gt;
&lt;input type="button" onclick="doSomething()" value="Do Something" /&gt;
&lt;form onsubmit="doSomething();"&gt;...</code></pre>
<p>That’s a very bad practice in that it is hard to manage and maintain. HTML and JS should not be mixed ever. You could do the same thing like this:</p>
<pre><code>&lt;a href="#" id="link"&gt;Some Action&lt;/a&gt;
&lt;input type="button" id="button" value="Do Something" /&gt;
&lt;form id="frm"&gt;...

&lt;script type="text/javascript"&gt;
var link = document.getElementById('link'),
 btn = document.getElementById('button'),
 frm = document.getElementById('link');

link.onclick = function(){
 // do something
};

btn.onclick = function(){
 // do something
};

frm.onsubmit = function(){
 // validate form
};     
&lt;/script&gt;</code></pre>
<p>This way it becomes easy to manage, maintain or enhance both HTML and JavaScript.</p>
<h2>9 – PUT SCRIPTS AT BOTTOM</h2>
<p>Normally scripts are put in <code>&lt;head&gt;&lt;/head&gt;</code> tags but this should be avoided. The reason for this is that browser loads your scripts sequentially and by the time they are loading, nothing else is done and website load times slow down (or at least that’s how visitors will perceive it) and you see actual output only after those scripts have been loaded by the browser.</p>
<p>The best practice is that scripts should be put on bottom of page just before closing body tag eg <code>&lt;/body&gt;</code>. This way browser will instantly display page and page load time will be better for users who view that page.</p>
<p>By the way, always put CSS on top in <code>&lt;head&gt;&lt;/head&gt;</code> tags because that’s something browser reads first and renders page’s layout accordingly.</p>
<p>Read more about this at famous <a href="http://developer.yahoo.com/performance/rules.html">Yahoo’s performance article</a>.</p>
<p>I would also suggest you to use Yahoo’s <a href="http://developer.yahoo.com/yslow/">YSlow</a> or Google’s <a href="http://code.google.com/speed/page-speed/">PageSpeed</a> add-on (add-ons of <a href="http://getfirebug.com/">Firebug</a>) which suggest you a lot of things on how to improve the performance of the page.</p>
<h2>10 – NEVER FORGET SEMI-COLON</h2>
<p>Always end statements and function expressions with a semi-colon:</p>
<pre><code>var name = 'some name'; // &lt;-------------

var myFunc = function(){
// some doe

}; // &lt;------------</code></pre>
<p>This is useful when you want to compress the code (for faster load times). If at any place, semi-colon isn’t present, you won’t be able to compress the code or wouldn’t get expected results most likely code-wise. You should always, always use semi-colons.</p>
<h2>BONUS</h2>
<p>The good news is that you can solve most of above problems by using <a href="http://www.jshint.com/">JSHint</a> or <a href="http://jslint.com/">JSLint</a> code quality tool. It will tell you about best-practices and any errors that might exist in your code. Having said that, it is good to improve your JS skills and avoid the need to go to such tools.</p>]]></description>
<link>https://codeinphp.github.io/post/javascript-best-practices</link>
<pubDate>Sun, 19 Apr 2015 10:00:00 +0500</pubDate>
</item>
<item>
<title>Exploring Lambda Functions and Closures in PHP</title>
<description><![CDATA[<h1>What is a Lambda Function</h1>
<p>A lambda function (also known as <strong>anonymous function</strong>) is a function that has:</p>
<ol>
<li>No Name</li>
<li>Can be assigned to a variable</li>
<li>Can be passed as argument to other functions or methods of a class</li>
</ol>
<p>In the past, this was possible with <a href="http://php.net/manual/en/function.create-function.php"><code>create_function</code></a> like:</p>
<pre><code>$multiply = create_function('$a, $b','return $a * $b;');
echo $multiply(5, 5); // 25</code></pre>
<p>But it was a nuisance if you needed to write longer anonymous functions using <code>create_function</code> because it was difficult to write function body that way inside quotes and then escaping quotes and stuff...</p>
<p>PHP 5.3 introduced true support of lambda/anonymous functions similar to how you see in Javascript, so you could write above code like:</p>
<pre><code>$multiply = function ($a, $b) {
    return $a * $b;
};

echo $multiply(5, 5); // 25</code></pre>
<p>As can be seen, above anonymous function has no name and has been assigned to variable  <code>$multiply</code>. You can also pass it other functions:</p>
<pre><code>function countEmails($number) {
    echo 'you have ' . $number . ' emails!';
}

$multiply = function ($a, $b) {
    return $a * $b;
};

echo countEmails($multiply(2, 5)); // you have 10 emails!</code></pre>
<p>You could have also written above like this if you wanted:</p>
<pre><code>function countEmails($multiply, $a, $b) {
    echo 'you have ' . $multiply($a, $b) . ' emails!';
}

$multiply = function ($a, $b) {
    return $a * $b;
};

echo countEmails($multiply, 2, 5); // you have 10 emails!</code></pre>
<p>And even like this:</p>
<pre><code>function countEmails($multiply, $a, $b) {
    echo 'you have ' . $multiply($a, $b) . ' emails!';
}

echo countEmails(function ($a, $b) {
    return $a * $b;
}, 2, 5); // you have 10 emails!</code></pre>
<p>You can also assign it to array:</p>
<pre><code>$array['multiply'] = function ($a, $b) {
     return $a * $b;
};

echo $array['multiply'](2, 10); // 20</code></pre>
<p>And even an object:</p>
<pre><code>$obj = new StdClass();

$obj-&gt;multiply = function ($a, $b) {
     return $a * $b;
};</code></pre>
<p>But caveat here is that instead of calling it like <code>echo $obj-&gt;multiply(2, 10)</code>, you would instead need to do:</p>
<pre><code>$multiply = $obj-&gt;multiply;
echo $multiply(2, 10); // 20</code></pre>
<p>Now let's create little program which says <code>Hello, World</code> using anonymous function:</p>
<pre><code>$message = 'Hello, World!';

$sayHello = function () {
    echo $message;
};

$sayHello();</code></pre>
<p>Oops, it results in error:</p>
<p><code>Notice: Undefined variable: message</code></p>
<p>It means anonymous function does not have access to <code>$message</code> inside it. This is exactly when we need a closure to have access to that <code>$message</code> variable.</p>
<h1>What is a Closure</h1>
<p>A closure is a lambda/anonymous function that is aware of its surrounding context through the use of <code>use</code> keyword. It can access a variable outside of the scope where it is defined. Consider last <code>$sayHello</code> anonymous function and we convert it into closure through the use of <code>use</code> keyword and gain access to the <code>$message</code> variable:</p>
<pre><code>$message = 'Hello, World!';

$sayHello = function () use ($message) {
    echo $message;
};

$sayHello(); // Hello, World!</code></pre>
<p>Thanks to closure (<code>use</code> keyword), we are now able to access <code>$message</code> variable!</p>
<hr />
<p>If you need to change the value of passed outside variable, you need to use reference of course:</p>
<pre><code>$message = 'Hello, World!';

$sayHello = function () use (&amp;$message) {
    echo $message;
    $message = 'Hello World Again!';
};

$sayHello(); // Hello, World!
$sayHello(); // Hello World Again!</code></pre>
<p>You can also pass regular arguments to closure:</p>
<pre><code>$message = 'World!';

$sayHello = function ($arg) use ($message) {
    echo $arg . ' ' . $message;
};

$sayHello('Hello'); // Hello, World!</code></pre>
<p>You can also create a recursive function using closure easily, here is example of how you can create a factorial function:</p>
<pre><code>$factorial = function( $n ) use ( &amp;$factorial ) {
    if( $n == 1 ) return 1;
    return $factorial( $n - 1 ) * $n;
};

echo $factorial( 5 );</code></pre>
<p>Notice that <code>$factorial</code> is passed by reference using <code>&amp;</code> otherwise it won't work.</p>
<hr />
<p>The difference between an anonymous function and closure is that closure has ability to access a variable outside of its scope by using the <code>use</code> keyword. So that is the subtle difference between an anonymous function and a closure. In fact, both are of them are instances of <code>Closure</code> class internally:</p>
<pre><code>// anonymous function
$multiply = function ($a, $b) {
    return $a * $b;
};

$message = 'Hello, World';

// closure
$sayHello = function () use ($message) {
    echo $message;
};

var_dump ($multiply instanceof Closure); // true
var_dump ($sayHello instanceof Closure); // true</code></pre>
<h1>Type Hinting</h1>
<p>We know that you can already type hint few things:</p>
<ul>
<li>Object</li>
<li>Array</li>
<li>Interface</li>
<li>callable</li>
</ul>
<p>But you can also type hint <code>Closure</code> as shown below:</p>
<pre><code>function multiply($number, Closure $closure)
{
    return $closure($number);
}

$closure = function($x){ return $x * 2; };
echo multiply(10, $closure);</code></pre>
<p>Here we have made <code>multiply</code> function to require type of <code>Closure</code> as second parameter.</p>
<h1>Use Cases</h1>
<p>Anonymous functions and closures can be used in variety of situations.</p>
<p><strong>As Callbacks</strong></p>
<p>You can use them in your custom functions as callback or some of the PHP's built-in functions such as <code>array_map()</code>, <code>array_reduce()</code>, <code>array_filter()</code>, <code>array_walk()</code>, etc. Let's take example of <code>array_walk()</code>. If you <a href="http://php.net/manual/en/function.array-walk.php">look at it's definition</a>, here is how it looks:</p>
<pre><code>bool array_walk ( array &amp;$array , callable $callback [, mixed $userdata = NULL ] )</code></pre>
<p>Notice the second parameter <code>callable $callback</code>. It means it expects something to be callable function. Anytime you see such parameter in some function definition, it means you can apply anonymous functions to it. Here is example:</p>
<pre><code>$myArray = array(1, 2, 3, 4, 5);

// multiply each array value with 2    
array_walk($myArray, function(&amp;$value, $index){
    $value *= 2;
});

print_r($myArray);

Array
(
    [0] =&gt; 2
    [1] =&gt; 4
    [2] =&gt; 6
    [3] =&gt; 8
    [4] =&gt; 10
)</code></pre>
<hr />
<p><strong>In Routing</strong></p>
<p>You might have seen closures being used in routing in framework like Laravel, Slim, Silex, etc:</p>
<pre><code>$app = new \Slim\Slim($options);

$app-&gt;get('/', function () use ($app) {
    $app-&gt;render('home', array('content' =&gt; 'Hello, World!!!'));
});</code></pre>
<p>Here <code>$app</code> is imported from outside scope into the scope of closure so that it can be used to render the view <code>$app-&gt;render(...)</code></p>
<hr />
<p><strong>Accessing Private Members of a Class</strong></p>
<p>We can use <a href="http://www.php.net/manual/en/closure.bind.php"><code>bind()</code></a> or <a href="http://www.php.net/manual/en/closure.bindto.php"><code>bindTo</code></a> methods of <code>Closure</code> class to access <code>private</code> data of some class, for example:</p>
<pre><code>class MyClass {
    private $variable = 'I am private variable!';
}

$closure = function() {
    return $this-&gt;variable;
};

$result = Closure::bind($closure, new MyClass(), 'MyClass');
echo $result(); // I am private variable!</code></pre>
<p>There you see, we were able to get value of private variable <code>$variable</code>.</p>
<p>Similarly, it is also possible to <strong>add new behaviour to a class without actuallly modifying it direclty</strong>. Pretty cool hun ?</p>
<hr />
<p><strong>Lazy-loading a Class</strong></p>
<p>Another <code>^cool^</code> thing you can do with closure is to lazy-load a class. For example:</p>
<pre><code>class MyClass {
    public function __construct() {
        echo 'I am initialized!';
    }
}

$getMyClass = function() {
    $myClass = new MyClass();
    return $myClass;
};</code></pre>
<p>If you run above code, you might expect to see <code>I am initialized!</code> message because one might think we are creating an instance of <code>MyClass</code>. That's not true though, because code inside <code>$getMyClass</code> anonymous function is not run until you actually call it:</p>
<pre><code>$myClass = $getMyClass();</code></pre>
<p>And now you would see the message <code>I am initialized!</code>. So this is pretty neat trick to defer some piece of code and use it only when you need it.</p>]]></description>
<link>https://codeinphp.github.io/post/exploring-lambda-functions-and-closures-in-php</link>
<pubDate>Sat, 18 Apr 2015 23:57:00 +0500</pubDate>
</item>
<item>
<title>Learning Javascript</title>
<description><![CDATA[<p>JavaScript is <a href="http://en.wikipedia.org/wiki/JavaScript">cross-platform</a>, cross-browser language; javascript is everywhere; web, <a href="http://en.wikipedia.org/wiki/Rich_Internet_application">RIA</a> (rich internet applications), <a href="http://sixrevisions.com/javascript/mobile%C2%A0web-development-frameworks/">mobile, tablets</a>, <a href="https://github.com/mrdoob/three.js/">animations</a> and even on server with the advent of <a href="http://nodejs.org/">node.js</a>. Javascript is the language of the future.</p>
<p>I started off with jQuery without knowing anything much about javascript because by the time I didn’t find any reason to learn it due to fact that  javascript libraries did everything we needed putting complexities out of the way. Today I realize that I chose the wrong path, a good understanding of javascript language is crucial if you look at the reasons I have mentioned in the very beginning but it is never too late to start again, that’s exactly what I have decided, learning javascript seriously. I am not the only one who has started realizing the power and future of javascript, there are <a href="http://shiflett.org/blog/2012/feb/learning-javascript">giants</a> who have started learning it too. If you are also javascript-library-only developer, or even <strong>copy-paster</strong> programmer, <a href="http://phpadvent.org/2009/you-really-need-to-learn-javascript-by-ed-finkler">you should really</a> <a href="http://net.tutsplus.com/tutorials/javascript-ajax/from-jquery-to-javascript-a-reference/?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed:%20nettuts%20%28Nettuts%2b%29">learn javascript</a> seriously !</p>
<p>Despite design flaws and bad reputation of the language <a href="http://javascript.crockford.com/javascript.html">as they say</a> and probably rightly so, javascript is popular and language of the choice for those who have gone into deeper <a href="http://ejohn.org/">understating</a> <a href="http://sstephenson.us/">of</a> <a href="http://infrequently.org/about-me/">it</a>. Javascript language <a href="http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/">does</a> <a href="http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/">have</a> <a href="http://www.svennerberg.com/2009/02/global-variables-in-javascript/">bad</a> <a href="http://lucumr.pocoo.org/2011/2/6/automatic-semicolon-insertion/">parts</a> but its <a href="http://www.amazon.com/dp/0596517742/?tag=stackoverfl08-20">good parts</a> over-weigh its bad parts and there is always room to avoid bad parts if you know the language right and use it effectively.</p>
<p>Javascript turns out to be extremely <a href="http://bonsaiden.github.com/JavaScript-Garden/">tricky</a> language, consider:</p>
<pre><code>// Comparison
'' == '0';    //false
0 == '';    // true
0 =='0';    // true

// Type checking
typeof null;    // object

// Scope
function myFunc() {
  return
  {
    name: 'sarfraz'
  };
}

var f = myFunc();
console.log(f);    // undefined</code></pre>
<p>I did <strong>a lot of research</strong> to find best javascript learning resources. On the journey of my exploration, I came across some of the great resources with a lot of reviews and user feedback. By now, if you made your mind to take javascript seriously, here are the best resources out there you should check out.</p>
<h2>Books</h2>
<ul>
<li><a href="http://shop.oreilly.com/product/9780596517748.do">JavaScript: The Good Parts</a> by <a href="http://crockford.com/">Douglas Crockford</a></li>
<li><a href="http://jsninja.com/">Secrets of the JavaScript Ninja</a> by <a href="http://ejohn.org/">John Resig</a></li>
<li><a href="http://jspro.org/">Pro JavaScript Techniques</a> by <a href="http://ejohn.org/">John Resig</a></li>
<li><a href="http://www.amazon.com/Performance-JavaScript-Faster-Application-Interfaces/dp/059680279X">High Performance JavaScript</a> by <a href="http://www.nczonline.net/blog/about/">Nicholas C. Zaka</a></li>
<li><a href="http://www.amazon.com/gp/product/B004XQX4K0/ref=pd_lpo_k2_dp_sr_3?pf_rd_p=486539851&amp;pf_rd_s=lpo-top-stripe-1&amp;pf_rd_t=201&amp;pf_rd_i=0596805527&amp;pf_rd_m=ATVPDKIKX0DER&amp;pf_rd_r=1GJCJ4PSFS8516NGDG28">JavaScript: The Definitive Guide</a> by <a href="http://www.davidflanagan.com/">David Flanagan</a></li>
</ul>
<h2>Online</h2>
<ul>
<li><a href="http://eloquentjavascript.net/">Eloquent JavaScript</a> by Marijn Haverbeke</li>
<li><a href="http://javascript.info/">The JavaScript Tutorial</a></li>
<li><a href="https://developer.mozilla.org/en/JavaScript/Guide">JavaScript Guide MDN</a></li>
<li><a href="http://bonsaiden.github.com/JavaScript-Garden/">JavaScript Garden</a> (For intermediate &amp; advanced programmers – must read !)</li>
</ul>
<h2>Videos</h2>
<ul>
<li><a href="http://learn.appendto.com/">appendto.com</a></li>
<li><a href="http://yuiblog.com/crockford/">Douglas Crockford’s JavaScript Video Series</a></li>
<li><a href="http://www.youtube.com/watch?v=hQVTIJBZook">JavaScript: The Good Parts</a></li>
</ul>
<h2>Blogs to Subscribe</h2>
<ul>
<li><a href="http://perfectionkills.com/">PerfectionKills</a></li>
<li><a href="http://dmitrysoshnikov.com/">Dmitry A. Soshnikov</a></li>
<li><a href="http://javascriptweblog.wordpress.com/">JavaScript, JavaScript</a></li>
<li><a href="http://www.adequatelygood.com/">Adequately Good</a></li>
<li><a href="http://ejohn.org/">John Resig</a></li>
<li><a href="http://www.2ality.com/">2ality</a></li>
<li><a href="http://nemisj.com/">Notes of Maks Nemisj</a></li>
<li><a href="http://addyosmani.com/blog/">Addy Osmani</a></li>
<li>Bonus: <a href="http://net.tutsplus.com/articles/web-roundups/30-developers-you-must-subscribe-to-as-a-javascript-junkie/">33 Developers you MUST Subscribe to as a JavaScript Junkie</a></li>
</ul>
<h2>Tools</h2>
<ul>
<li><a href="http://gruntjs.com/">Grunt</a> (The JavaScript Task Runner)</li>
<li><a href="http://www.jshint.com/">JSHint</a> (JS Code Quality Tool)</li>
<li><a href="http://jsperf.com/">JSPerf</a> (JS Performance Testing)</li>
<li><a href="http://www.jsunit.net/">JSUnit</a> (JS Unit Testing)</li>
<li><a href="http://siliconforks.com/jscoverage/">JSCoverage</a> (JS Code Coverage)</li>
<li><a href="http://code.google.com/p/jsdoc-toolkit/">JDDoc-Toolkit</a> (JS Documentation Tool)</li>
<li>Bonus: <a href="http://coding.smashingmagazine.com/2009/02/08/50-extremely-useful-javascript-tools/">50 Useful JavaScript Tools</a></li>
</ul>]]></description>
<link>https://codeinphp.github.io/post/learning-javascript</link>
<pubDate>Sat, 18 Apr 2015 20:35:00 +0500</pubDate>
</item>
<item>
<title>Abstract Class vs Interface</title>
<description><![CDATA[<p>I found this picture that tells the difference between <code>abstract class</code> and <code>interface</code>:</p>
<p><img src="https://codeinphp.github.io/images/142937584655328b66dcedc.png" alt="enter image description here" /></p>
<hr />
<p>Let's see each comparison practically so we know what it means.</p>
<pre>
Interface support multiple inheritance | Abstract class does not support multiple inheritance
</pre>
<p>It means you can extend an <code>interface</code> with one or more (hence <em>multiple inheritance</em>) interfaces like:</p>
<pre><code>interface Interface_A { }
interface Interface_B { }
interface Interface_C { }

interface MyInterface extends Interface_A, Interface_B, Interface_C { }</code></pre>
<p>As can be seen, we are extending <code>MyInterface</code> with three other interfaces <code>Interface_A</code>, <code>Interface_A</code> and <code>Interface_C</code>.</p>
<p>Let's now try to extend an <code>abstract class</code>:</p>
<pre><code>class Class_A { }

abstract class MyAbstractClass extends Class_A { }</code></pre>
<p>No problem there, you CAN extend an abstract class with exactly one class but if you try to add one more:</p>
<pre><code>class Class_A { }
class Class_B { }

abstract class MyAbstractClass extends Class_A, Class_B { }</code></pre>
<p>This time PHP would give you strange error without telling you what you are doing wrong:</p>
<p><code>Parse error: syntax error, unexpected ',', expecting '{'</code></p>
<p>I wish PHP would have given message somewhat like (hope PHP gives smarter error messages in future versions):</p>
<p><code>Fatal Error: You cannot extend an abstract class with more than one classes</code></p>
<hr />
<pre>
Interface does'n Contains Data Member | Abstract class contains Data Member
</pre>
<p>By data members, it means class properties or variables. So you cannot add data members to an interface:</p>
<pre><code>interface MyInterface {
    public $foo = null;
}</code></pre>
<p>So in an interface, only method stubs can be provided.</p>
<p>You can add data members to an abstract class though, this is valid code of course:</p>
<pre><code>abstract class MyAbstractClass {
    public $foo = null;
}</code></pre>
<hr />
<pre>
Interface does'n contains Constructors | Abstract class contains Constructors
</pre>
<p>It sounds like this point applies to may be other languages but in PHP an interface CAN have an empty constructor shell:</p>
<pre><code>interface MyInterface {
    public function __construct();
}</code></pre>
<p>Like other languages, PHP shouldn't have allowed having a constructor inside an interface. But anyways, it doesn't make much sense here and should be avoided anyway.</p>
<p>On the other hand, an abstract class can contain constructor method:</p>
<pre><code>abstract class MyAbstractClass {
    abstract public function __construct();
}</code></pre>
<p>Here constructor is said to be <code>abstract</code> and therefore expends child classes to complement for it. However, you can also have common initialization code in constructor of an abstract class too in which case, you would need to remove the <code>abstract</code> keyword and provide the body for it:</p>
<pre><code>abstract class MyAbstractClass {
    public function __construct() {
         // initialization code
    };
}</code></pre>
<hr />
<pre>
An interface Contains only incomplete member (signature of member) | An abstract class Contains both incomplete (abstract) and complete member
</pre>
<p>This simply means an interface can only contain method stubs not their implementation. This is pretty same as second point in the image above. This is why in methods of an interface, they don't have bodies marked with <code>{ }</code> braces. So an interface is completely empty shell that enforces some rules that child classes must implement and that's it.</p>
<p>Abstract classes can have both; empty method definitions as well as full method implementation. Generally empty method stubs are prefixed with <code>abstract</code> keyword so that child classes must provide their implementation details. But an abstract class can also contain full method implementation inside it which are generally used for common piece of functionality that each child class may need. For example:</p>
<pre><code>abstract class Animal {
    // child classes must implement this
    abstract function prey();

    public function run() {
        echo 'I am running!';
    }
}

class Dog extends Animal {
    public function prey() {
        echo 'I killed the cat !';
    }
}

class Cat extends Animal {
    public function prey() {
        echo 'I killed the rat !';
    }
}

$dog = new Dog();
$cat = new Cat();

$dog-&gt;prey(); // I killed the cat !
$cat-&gt;prey(); // I killed the rat !

$dog-&gt;run(); // I am running!
$cat-&gt;run(); // I am running!</code></pre>
<p>In above code, we can see that <code>Animal</code> class has one <code>abstract</code> method called <code>prey</code> because each child class (animal) have their own ways of finding prey and a full implemented method called <code>run</code> because all animals can run, this doesn't need to be defined in each of child classes. So here <code>run</code> method is fully implemented and represents common data that needs to be shared across child classes.</p>
<p>Notice that other than common fully implemented methods inside an abstract class, you can also have common data members eg variables that need to be shared across child classes.</p>
<hr />
<pre>
An interface cannot have access modifiers by default everything is assumed as public | An abstract class can contain access modifiers for the subs, functions, properties
</pre>
<p>By access modifiers, we mean ability to change scoping by using keywords like <a href="http://stackoverflow.com/questions/4361553/php-public-private-protected"><code>public</code>, <code>private</code> and <code>protected</code></a>. We cannot use these for interfaces but we can use them for everything in abstract classes.</p>
<hr />
<pre>
Members of interface can not be Static | Only Complete Member of abstract class can be Static
</pre>
<p>This is again possible in PHP (as of now with PHP 5.4) unlike other languages, so you CAN do:</p>
<pre><code>interface MyInterface {
    static function foo();
}</code></pre>
<p>Notice the addition of keyword <code>static</code> to mark it as static method.</p>
<p>For abstract class, you can have static members as well as those methods that are implemented in the abstract class:</p>
<pre><code>abstract class MyAbstractClass {
    public static $foo = null;

    public static function foo() {}
}</code></pre>
<p>But you cannot have a method to be both <code>static</code> and <code>abstract</code>, so you cannot do this, which is common across the languages:</p>
<pre><code>abstract class MyAbstractClass {
    public static $foo = null;

    abstract static function foo() {} // error
}</code></pre>
<hr />
<p>In conclusion, interface and abstract classes are completely different from each other, you cannot interchange them or use one as alternative over the other. Interfaces are completely empty shells that expect child classes to implement everything for them. On the other hand, abstract class can not only contain <em>common piece of information</em> by implementing inside them but also expect child classes to fill in the remaining gaps.</p>]]></description>
<link>https://codeinphp.github.io/post/abstract-class-vs-interface</link>
<pubDate>Sat, 18 Apr 2015 20:26:00 +0500</pubDate>
</item>
<item>
<title>PHPExecute – PHP Code Runner</title>
<description><![CDATA[<p>Often times, you quickly need to test some PHP code. To do so, you create a file, put it in web root folder, write some code in it, open its URL and then you see its output. This is kind of lot of work and I often need a way to quickly test my PHP code. This requirement made me create my own code testing tool, <strong>PHPExecute</strong>.</p>
<p>PHPExecute is the fastest way to test PHP code. You write the code, hit the execute button, an ajax request is triggered and you see the output fast without page refresh. Here are some of the cool things about it:</p>
<ul>
<li>Very fast way to test your code</li>
<li>Nice friendly interface</li>
<li>Code  Highlighting</li>
<li>Useful PHP, system information panel</li>
<li>Saving favorite code snippets</li>
<li>Adding useful classes</li>
<li>Easy to extend as per your needs</li>
</ul>
<p><strong>Screenshot</strong></p>
<p><img src="https://codeinphp.github.io/images/1428864689552abeb12a929.gif" alt="enter image description here" /></p>
<h2>Extending PHPExecute</h2>
<p>The good thing is that you can download (see below) it, see its source code and extend it however you like according to your needs. For example, you can add classes for testing, performance or any other purpose. One can even integrate bash commands (I am not going into details of that) to make it even more useful tool to work with.</p>
<h2>Usage Notes</h2>
<ul>
<li>
<p>PHPExecute uses <a href="http://php.net/manual/en/function.eval.php"><code>eval</code></a> function to run the code. It is strongly recommended that you should use that tool for local testing only and not on production server due to security reasons. If you do, you use it on your own risk.</p>
</li>
<li>
<p>In order to save snippets, PHPExecute uses <a href="http://en.wikipedia.org/wiki/Web_Storage">localStorage</a> feature which is available in latest browsers (and IE9+) only and also it can be around <strong>5MB</strong> in size. This isn’t that ideal if you are going to save a lot of snippets but you can always extend PHPExecute to add database support and save your snippets there.</p>
</li>
<li>The custom functions that can be used in PHPExecute can be found in <strong>includes/functions.php</strong> file. You can add any functions in that file that you want to use directly inside PHPExecute. The custom functions can also be seen in <strong>PHP Info &gt; User Defined Functions</strong>.</li>
</ul>
<hr />
<p><strong>Download</strong></p>
<p><a href="https://github.com/sarfraznawaz2005/PHPExecute">Download PHPExecute at Github</a></p>
<p>I hope PHPExecute turns out to be a useful tool for you. Please do share if you add anything to it via comments so that we could know it and integrate ourselves too :)</p>]]></description>
<link>https://codeinphp.github.io/post/phpexecute-php-code-runner</link>
<pubDate>Sun, 12 Apr 2015 20:57:00 +0500</pubDate>
</item>
<item>
<title>Outputting PHP To Browser Console</title>
<description><![CDATA[<p>Although there exist <strong>classes</strong> for outputting PHP to browser console such as Google’s <strong>PHP Console</strong> and certain others, I was looking for a way to output PHP to browser console without including those classes in my PHP files or installing any browser plugin to do the same. Currently, I am working on Facebook application development in which you have to commit/upload the code to check certain output out of PHP unlike offline development where you check the code output before committing it up. This makes Facebook application development a longer process for a developer but you got to live with it because you don’t have a choice.</p>
<p>Anyways, to speed up the code output checking process a little and rather using <code>debug_backtrace</code>, <code>print_r</code>, <code>print</code>, <code>echo</code>, <code>var_dump</code>, etc which you need to remove/comment again, I created a function to get output of PHP on the browser console. One could use <code>error_log</code> function but even that makes you go to your log file and then see the output. Of course, browser needs to support/have the console so that code result is output there. Because IE less than 8 doesn't have console, this won’t work in IE less than 8, though result won’t be affected in it. Notice that you can see console in IE=&gt;8 by pressing <kbd>F12</kbd> key and then going to <strong>Script</strong> tab where you need to make sure <strong>Console</strong> tab is selected on the right side.</p>
<p>Here is the function:</p>
<pre><code> /**
 * Logs messages/variables/data to browser console from within php
 *
 * @param $name: message to be shown for optional data/vars
 * @param $data: variable (scalar/mixed) arrays/objects, etc to be logged
 * @param $jsEval: whether to apply JS eval() to arrays/objects
 *
 * @return none
 * @author Sarfraz
 */
 function logConsole($name, $data = NULL, $jsEval = FALSE)
 {
      if (! $name) return false;

      $isevaled = false;
      $type = ($data || gettype($data)) ? 'Type: ' . gettype($data) : '';

      if ($jsEval &amp;&amp; (is_array($data) || is_object($data)))
      {
           $data = 'eval(' . preg_replace('#[\s\r\n\t\0\x0B]+#', '', json_encode($data)) . ')';
           $isevaled = true;
      }
      else
      {
           $data = json_encode($data);
      }

      # sanitalize
      $data = $data ? $data : '';
      $search_array = array("#'#", '#""#', "#''#", "#\n#", "#\r\n#");
      $replace_array = array('"', '', '', '\\n', '\\n');
      $data = preg_replace($search_array,  $replace_array, $data);
      $data = ltrim(rtrim($data, '"'), '"');
      $data = $isevaled ? $data : ($data[0] === "'") ? $data : "'" . $data . "'";

$js = &lt;&lt;&lt;JSCODE
\n&lt;script&gt;
 // fallback - to deal with IE (or browsers that don't have console)
 if (! window.console) console = {};
 console.log = console.log || function(name, data){};
 // end of fallback

 console.log('$name');
 console.log('------------------------------------------');
 console.log('$type');
 console.log($data);
 console.log('\\n');
&lt;/script&gt;
JSCODE;

      echo $js;
 } # end logConsole</code></pre>
<p>Here is an example of how to use it:</p>
<pre><code>$name = 'sarfraz';
$fruits = array("banana", "apple", "strawberry", "pineaple");

$user = new stdClass;
$user-&gt;name = "Sarfraz";
$user-&gt;desig = "Sr. Software Engineer";
$user-&gt;lang = "PHP";

logConsole('$name var', $name, true);
logConsole('An array of fruits', $fruits, true);
logConsole('$user object', $user, true);</code></pre>
<p>It would result in:</p>
<p><img src="https://codeinphp.github.io/images/1428862620552ab69c5381f.gif" alt="enter image description here" /></p>
<p>Although this does not prevent committing code first to see the code output if you are on facebook application development but it defintely does save some time. I have been using this function successfully so far, please let me know your ideas if any on how to improve this piece of code further. </p>]]></description>
<link>https://codeinphp.github.io/post/outputting-php-to-browser-console</link>
<pubDate>Sun, 12 Apr 2015 20:23:00 +0500</pubDate>
</item>
<item>
<title>My Local Development Workflow with WAMP/XAMPP, GIT and Google Drive</title>
<description><![CDATA[<p>I like to share my local development workflow which has turned out to be <strong>extremely useful</strong> in that all my projects’ files are <strong>version-ed and on the cloud</strong>. I use <strong>git</strong> to keep my files versioned and <strong>Google Drive</strong> so that I can access my projects anywhere. In this post, I will share really cool stuff that you definitely should consider implementing for your own projects.</p>
<p>If you don’t know about git and its benefits, there are numerous compelling reasons why it is useful, you might want to check out:</p>
<ul>
<li><a href="http://learn.github.com/p/intro.html">Introduction To Git</a></li>
<li><a href="http://www.gitology.com/chapter/benefits-of-using-git">The Benefits of Using Git</a></li>
<li><a href="http://coding.smashingmagazine.com/2011/07/26/modern-version-control-with-git-series/">Modern Version Control With Git</a></li>
<li><a href="http://whygitisbetterthanx.com/#svn">whygitisbetterthanx.com</a></li>
</ul>
<p>The benefits of keeping all my files and projects on the cloud like Google Drive should be obvious but if you are still not sure, check out:</p>
<ul>
<li><a href="http://www.salesforce.com/uk/socialsuccess/cloud-computing/why-move-to-cloud-10-benefits-cloud-computing.jsp">Why Move to the Cloud? 10 Benefits of Cloud Computing</a></li>
<li><a href="http://www.go-oodles.com/index.php/2012/08/the-six-key-business-benefits-of-google-drive/">The Six Key Business Benefits of Google Drive</a></li>
</ul>
<p>Although there are many other cloud storage services such as <a href="https://skydrive.live.com/">Microsoft SkyDrive</a>, <a href="https://www.dropbox.com/">Dropbox</a>, <a href="https://www.box.com/">Box</a>, <a href="http://www.bitcasa.com/">Bitcasa</a>, etc but I chose Google Drive since it gives 10GB of free space which should be enough for my development needs. If that’s not enough for you, you can create another Gmail account and get another 10GB free. You might want to read their usage policies too if you want.  You may also consider using Bitcasa which gives you unlimited space but since it is new, I can’t personally trust it as yet.</p>
<h2>Installing Google Drive</h2>
<p><strong>Step 1:</strong> <a href="https://mail.google.com/">Create a new Gmail account</a> to be used with Google Drive client software. Although you can use your existing account but it is good idea to create a new one used for your projects’ backup only.</p>
<p><strong>Step 2:</strong> Download Google Drive from <a href="https://tools.google.com/dlpage/drive">here</a> or <a href="http://filehippo.com/download_google_drive/">here</a>. During the installation, you would be asked to specify the folder path which will be synchronized with Google Drive. Make sure that you specify a folder present on any drive other than your OS drive so that even if your system crashes or corrupts, your projects remain intact. For example, I have that folder on path D:/Google Drive/</p>
<p><strong>Step 3:</strong>  Once installed, run Google Drive software and specify the credentials of your newly created Gmail account.</p>
<h2>Using Google Drive with WAMP/XAMPP</h2>
<p>Now that we’ve setup google drive, it is time to setup document root to google drive folder and create virtual host. This would allow you to run your local projects through WAMP/XAMPP from google drive folder. The reason why we do this is that since google drive folder will be sync by google drive software, any project we put in that folder will automatically be uploaded in your google drive account.</p>
<blockquote>
<p><strong>Note:</strong> I am using XAMPP but if you are using WAMP, some settings or file paths might be different, you should consider reading its
documentation.</p>
</blockquote>
<p><strong>Step 1:</strong> Inside your google drive folder, create a new folder named <strong>webroot</strong> making whole path <strong>X:\Google Drive\webroot</strong> where <strong>X</strong> represents your drive letter.</p>
<p><strong>Step 2:</strong> Assuming you have specified google drive folder to be  <strong>D:/Google Drive/</strong>, open <strong>httpd.conf</strong> (normally located at <strong>apache\conf</strong> folder) file in notepad or other text editor and find the line <strong>Include “conf/extra/httpd-vhosts.conf”</strong>. If there is a hash (#) before that line, remove it. Now find the line with <strong><Directory /></strong> and you should see something similar to:</p>
<pre><code>&lt;Directory /&gt;
   AllowOverride none
   Require all denied
&lt;/Directory&gt;</code></pre>
<p>Change <strong>Require all denied</strong>  to <strong>Require all granted</strong></p>
<p>Or if you see something like:</p>
<pre><code>&lt;Directory /&gt;
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
&lt;/Directory&gt;</code></pre>
<p>Change it to:</p>
<pre><code>&lt;Directory /&gt;
    ........
    Allow from all
&lt;/Directory&gt;</code></pre>
<p>Now come to bottom of the file and add:</p>
<pre><code>&lt;Directory "D:\Google Drive\webroot"&gt;
  Options Indexes MultiViews
  Order Allow,Deny
  Allow from all
&lt;/Directory&gt;</code></pre>
<p>Save the file and close it.</p>
<p><strong>Step 3:</strong> Open <strong>httpd-vhosts.conf</strong> (normally located at <strong>apache\conf\extra</strong> folder) and add these lines at the end of it:</p>
<pre><code>&lt;VirtualHost 127.0.0.1:80&gt;
    DocumentRoot "D:/Google Drive/webroot"
    ServerName gdroot.loc
    ServerAlias gdroot.loc
    ErrorLog "D:/Google Drive/webroot/logs/error.log"
    CustomLog "D:/Google Drive/webroot/logs/access.log" combined
&lt;/VirtualHost&gt;</code></pre>
<p>Save the file and close it. Notice that we have specified <strong>gdroot.loc</strong> as address which actually means google drive root (<strong>.loc</strong> signals that it is local folder) which actually maps to your google drive webroot folder eg <strong>D:/Google Drive/webroot</strong>. Notice that you could name it anything you want like <strong>mycoolwebsite.com, yourname.com</strong>, etc but of course that is local folder running from your own computer.</p>
<p><strong>Step 4:</strong> Open <strong>hosts</strong> file in notepad or other text editor located at <strong>X:\Windows\System32\drivers\etc</strong> where <strong>X</strong> stands for drive letter where your OS is installed. At the end of that file add this line assuming you specified URL in above step as <strong>gdroot.loc</strong>:</p>
<pre><code>127.0.0.1       gdroot.loc</code></pre>
<p>Or if you also use port to access your LAMP/XAMPP URLs, specify that as well:</p>
<pre><code>127.0.0.1:PORT_NUMBER_HERE       gdroot.loc</code></pre>
<blockquote>
<p><strong>Note:</strong> If you can’t edit hosts file, you need to have file owner permission, search on Google how to do that.</p>
</blockquote>
<p>Restart apache and access the new url by typing <strong>gdroot.loc</strong> in your browser. You should see screen similar to when you go to <a href="http://localhost">http://localhost</a>.</p>
<p>Congratulations ! you have a nice workflow now. You can now put all your existing our new projects inside your new document root which was assumed to be located at <strong>D:\Google Drive\webroot</strong> and now all your projects are sync with google drive and automatically uploaded to your google account which you can access anywhere. For example, you can now access your projects at office or any other computer by installing google drive client software  there and telling it sync/download your webroot folder. Your projects are now always there and backed up on the cloud :)</p>
<p>Let’s take cool stuff one step further by using <strong>git</strong> so that our projects file are also <strong>version-ed</strong>. If you don’t know much about git and its benefits consider reading links posted above or below in the <strong>Git Resources</strong> section.</p>
<h2>Using Git with a Central Repository</h2>
<p>Creating and using central repository is especially useful in a team. If you just want to keep your projects version-ed and are the only developer working on a project, the normal flow is (unless you track your project to remote host such as <a href="http://github.com/">github</a>):</p>
<ul>
<li>modify files</li>
<li>commit your changes</li>
<li>repeat</li>
</ul>
<p>So essentially you can skip this section if you just want to version your project files and are only developer working on a project.</p>
<p><strong>Step 1:</strong> Download msysgit from <a href="http://code.google.com/p/msysgit/downloads/list">here</a>, choose first link from there. Install it with default settings.</p>
<p><strong>Step 2:</strong> Go to your google drive folder (<strong>D:\Google Drive\</strong>) and create a new folder there named <strong>central.git</strong></p>
<p><strong>Step 3:</strong> Right click on newly created folder and choose <strong>Git Bash Here</strong> and type: </p>
<pre><code>git init –bare</code></pre>
<p><strong>Step 4:</strong> Create a test project folder named <strong>myproject</strong> inside your normal WAMP/XAMPP webroot/htdocs folder or google drive webroot folder mentioned above (Although you can git-manage any folder anywhere on the drive but naturally we want to git-manage projects that we run from webroot/htdocs folder).</p>
<p><strong>Step 5:</strong> Right click on newly created folder, choose <strong>Git Bash Here</strong> and issue these commands one by one:</p>
<pre><code>git init
git remote add central /e/Google\ Drive/central.git/
git push --all central
git push --set-upstream-to central master</code></pre>
<p>Great! now we’ve setup central repository for all our git-managed projects and we can commit, push, fetch all changes from that central repository. For any new repository, you can now issue commands like:</p>
<pre><code>git clone /e/Google\ Drive/central.git/
git fetch /e/Google\ Drive/central.git/
git push central
and so on</code></pre>
<p>That's it.</p>
<h2>Git Resources</h2>
<ul>
<li><a href="http://learn.github.com/p/intro.html">Introduction To Git</a></li>
<li><a href="http://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide">Git for beginners: The definitive practical guide</a></li>
<li><a href="http://net.tutsplus.com/tutorials/other/easy-version-control-with-git/">Easy Version Control with Git</a></li>
<li><a href="http://git-scm.com/book">Pro Git Book</a></li>
<li><a href="http://gitref.org/">Git Reference</a></li>
<li><a href="http://net.tutsplus.com/?s=git">and more</a></li>
</ul>]]></description>
<link>https://codeinphp.github.io/post/my-local-development-workflow-with-wamp-xampp-git-and-google-drive</link>
<pubDate>Sun, 12 Apr 2015 13:24:00 +0500</pubDate>
</item>
<item>
<title>GoodTodo PHP and SQlite App</title>
<description><![CDATA[<p>I really like to keep track of tasks and projects (personal or otherwise) I work on. I used to keep my todos list in notepad or by using some other sticky notes application but I wanted dead simple todos app with beautiful looks and simple to use without irrelevant options or goodies. So here I introduce GoodTodo; a todo app made via PHP and SQlite. I chose SQlite because I wanted to make sure that app is portable and of course since it’s small todo app, choosing SQlite for it makes perfect sense. I have used <a href="http://flightphp.com/">flightPHP</a> framework and <a href="http://j4mie.github.io/idiormandparis/">idiorm ORM</a> for it.</p>
<p>Here are its screenshots:</p>
<p><img src="https://codeinphp.github.io/images/1428836471552a507761961.png" alt="enter image description here" /></p>
<p><img src="https://codeinphp.github.io/images/1428836475552a507b38615.png" alt="enter image description here" /></p>
<p><img src="https://codeinphp.github.io/images/1428836467552a50733de24.png" alt="enter image description here" /></p>
<p><strong>How to use:</strong></p>
<p>Make sure you have wamp/xampp or other stack installed. Download the app and put in www/htdocs folder and browse to that folder via browser something like <a href="http://localhost/todo">http://localhost/todo</a>. Please make sure you have sqlite extension turned on from php.ini if it isn’t already.</p>
<p>So go ahead and <a href="https://dl.dropboxusercontent.com/u/11600057/todo.zip">download GoodTodo</a> to keep track of your todos.</p>]]></description>
<link>https://codeinphp.github.io/post/goodtodo-php-and-sqlite-app</link>
<pubDate>Sun, 12 Apr 2015 13:03:00 +0500</pubDate>
</item>
<item>
<title>BloggerCMS  - An Static Blog Generator CMS</title>
<description><![CDATA[<p>In the <a href="https://codeinphp.github.io/post/welcome.html">last post</a>, I had mentioned about BloggerCMS which is used to build this very blog. BloggerCMS is dead simple CMS that can be used to create fully functional static blogs. Although there are <a href="https://github.com/pinceladasdaweb/Static-Site-Generators#php">quite some static site generators</a> out there but I created BloggerCMS because I was missing these features in any of those static site generators:</p>
<ul>
<li>Web interface that allows me to create blog posts, add pages and more instead of writing blog posts manually in bunch of different text files</li>
<li>Markdown editor with live preview feature so that I don't have to type Markdown syntax myself</li>
<li>I needed a true blog generator instead of generic/advanced site generator</li>
</ul>
<p>Those three things are the driving force why I created BloggerCMS. Here is complete list of features of BloggerCMS as of now:</p>
<ul>
<li><strong>Graphical User Interface</strong> - manage your site via a browser</li>
<li><strong>File-based</strong> - no database required</li>
<li><strong>Truly Static</strong> - no server-side languages needed</li>
<li><strong>Portability</strong> - copy, move, backup or version control your site easily</li>
<li><strong>Integrated Markdown Editor</strong> - no need to know Markdown</li>
<li><strong>Built-in Images Manager</strong></li>
<li><strong>Disqus Commenting System</strong></li>
<li><strong>Search Posts Feature</strong></li>
<li><strong>Pagination</strong></li>
<li><strong>Responsive Layout</strong> - get started easily with the included responsive layout</li>
<li><strong>RSS Support</strong></li>
<li><strong>Sitemap Support</strong></li>
<li><strong>Google Analytics</strong></li>
<li><strong>Code Highlight Support</strong></li>
<li><strong>Tags Cloud Support</strong></li>
<li><strong>Social Follow Section</strong></li>
<li><strong>Categories Section</strong></li>
<li><strong>Archives Section</strong></li>
</ul>
<p>To know more about BloggerCMS, head over to <a href="https://bloggercms.github.io">it's blog</a> or see <a href="https://bloggercms.github.io/post/introducing-bloggercms.html">introductory post</a>.</p>]]></description>
<link>https://codeinphp.github.io/post/bloggercms-an-static-blog-generator-cms</link>
<pubDate>Mon, 06 Apr 2015 21:41:00 +0500</pubDate>
</item>
<item>
<title>Welcome !</title>
<description><![CDATA[<p><strong>Hello, World !</strong></p>
<p>This is my first post on this blog hosted at awesome <a href="https://pages.github.com/">github pages</a>. Previously I used to blog on wordpress <a href="http://sarfraznawaz.wordpress.com">here</a> but I switched to github pages because I really wanted to have static blog with free hosting and ability to write up quick posts using <a href="http://en.wikipedia.org/wiki/Markdown">Markdown</a> syntax. In the <a href="https://codeinphp.github.io/post/bloggercms-an-static-blog-generator-cms.html">next post</a>, I will write about <strong><a href="https://bloggercms.github.io">BloggerCMS</a></strong>, a CMS I have made that helps create static blogs. This blog has also been generated via BloggerCMS :)</p>
<p>On this blog, I intend to write my ideas mainly about PHP as well as other related web development technologies. </p>
<p><em>Stay tuned :)</em></p>]]></description>
<link>https://codeinphp.github.io/post/welcome</link>
<pubDate>Sun, 05 Apr 2015 15:46:00 +0500</pubDate>
</item>
</channel>
</rss>
