Preparing Your Pull Request For Code Review

Anyone that is working in a team and is collaborating with others on writing applications is using some form of version control system (VCS). The word collaborating is the important one and to achieve a good level of collaboration, people usually create pull requests in their software development tool of choice, be it GitHub, Bitbucket, GitLab or one of many other out there.

Pull requests are containers for commits that you have done, communication around those commits and changes therein, a code review entry point as well as some other things.

Continue reading “Preparing Your Pull Request For Code Review” »

Caching Part 1: Intro

What Is Caching And Why Should You Use It?

Anyone that has ever worked with high volume sites has at some point had to optimize one or more parts of the application. The most common ways to go about that are profiling the application code and database queries. Once you know where the bottlenecks are, you have a couple of options, depending on the use case:

  • refactoring the code so it runs faster, such as extracting code from foreach loops or optimizing the SQL,
  • offloading the process to the background (I wrote about that in another post),
  • cache the results

Continue reading “Caching Part 1: Intro” »

Using Google API to get Google Analytics data with PHP

You might have a need to display data from Google Analytics on your website like number of product page views in your webshop CMS. To achieve that, you would request the page views and maybe sessions (unique visits) for a certain URL from Google Analytics. If you’re using PHP, Google created Google API PHP client to help you do that. In this tutorial we’re going to use Server to Server Application authentication mechanism called two-legged OAuth.

Continue reading “Using Google API to get Google Analytics data with PHP” »

Quick File Opening in NetBeans

NetBeans is an irreplaceable tool for my every day use. Yes, it’s written in boring, slow Java, but the feature set is great and it helps me to get my tasks done without getting in my way. There are some things that could be better or more responsive. One of those things are code scanning and opening files. I like how Sublime Text 2 does the file open (Go to Anything), and this is how to achieve this in NetBeans.

First, without any plugins, you can type ALT + SHIFT + O which brings up the Go to File dialogue. It is ok, but it doesn’t provide the fuzzy search (you can emulate it by putting * between letters). To achieve fuzzy searching, we need the help of a plug-in called Open File Fast. Plug-in is last reported to run with NetBeans 6.9, but I’m running it with latest, 7.2. To install and configure it, follow these steps:

  • Go to http://plugins.netbeans.org/plugin/16495/open-file-fast and download for the latest version
  • In NetBeans, go to Tools → Plugins → Downloaded → Add Plugins, select the downloaded file and click Install (http://wiki.netbeans.org/FaqPluginInstall)
  • Restart NetBeans (although it is not needed to run the plug-in, I found that I couldn’t set key short cut for Open File Fast)
  • Now for the short cut. Go to Tools → Options → Keymap, search for “open file fast” → Assign short cut
I’ve assigned it CTRL + P. It still isn’t near as fast as Sublime Text, but it gets the job done.

Doctrine2 CLI under Silex application

I got it running with Doctrine 2.3.1-DEV. Get doctrine provider using composer:

{
    "minimum-stability": "dev",
    "require": {
        "silex/silex": "1.0.*",
        "taluu/doctrine-orm-provider" : "*",
    },
 
    "autoload": {
        "psr-0": { "Entity": "app/" }
    }
}

Create doctrine.php and put the following content inside. I like to put it in bin/doctrine.php:

#!/usr/bin/env php5
<?php
// Load your bootstrap or instantiate application and setup your config here
 
require_once APP_ROOT .'/vendor/autoload.php';
 
$app        = new Silex\Application();
 
// Doctrine DBAL
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
    'db.options' => $config['db']
));
 
// Doctrine ORM, I like the defaults, so I've only modified the proxies dir and entities path / namespace
$app->register(new Nutwerk\Provider\DoctrineORMServiceProvider(), array(
    'db.orm.entities'              => array(array(
        'type'      => 'annotation',
        'path'      => APP_PATH .'/Entity',
        'namespace' => 'Entity',
    )),
    'db.orm.proxies_dir'           => APP_ROOT .'/var/cache/doctrine/Proxy',
));
 
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
use Doctrine\ORM\Tools\Console\ConsoleRunner;
use Symfony\Component\Console\Helper\HelperSet;
 
$helperSet = new HelperSet(array(
    'db' => new ConnectionHelper($app['db.orm.em']->getConnection()),
    'em' => new EntityManagerHelper($app['db.orm.em'])
));
 
ConsoleRunner::run($helperSet);

And that’s it :)

Development environment

This is a quick post on how to set up your own DNS server with custom TLDso you can easily and more quickly get started on your next project. I am doing my programming on the Linux machine (Ubuntu to be Precise :)). The idea behind this set-up is to evade the need to ever modify your /etc/hosts file. Also, there is a possibility to even skip the creating of Apache VirtualHost directive and restarting the web server. Onward with the How-To.

Disclaimers:

  • I use Ubuntu, so substitute apt-get with yum or what ever you use
  • Anywhere you see the IP 192.168.1.253, replace with your own
  • I haven’t set up any forwarders in named.conf.options

Install and configure DNS (BIND9)

sudo apt-get install bind9

Edit these files

/etc/bind/named.conf.local:

zone "dev" {
    type master;
    file "/etc/bind/db.dev";
};

zone "1.168.192.in-addr.arpa" {
    type master;
    file "/etc/bind/db.192.168.1";
};

/etc/bind/db.dev

$TTL	604800
@		IN		SOA		dev. root.dev. (
	             2012042301		; Serial
			 604800		; Refresh
			  86400		; Retry
			2419200		; Expire
			 604800 )	; Negative Cache TTL
;
@		IN		NS	dev.
@		IN		A	192.168.1.253
*.dev.	14400 	IN 		A	192.168.1.253

/etc/bind/db.192.168.1:

$TTL	604800
@		IN		SOA		dev. root.dev. (
	     2012042301		; Serial
			 604800		; Refresh
			  86400		; Retry
			2419200		; Expire
			 604800 )	; Negative Cache TTL
;
@		IN		NS		dev.
253		IN 		PTR		dev.

Be careful to replace 253 in your files for your own last IP octet. Also, the filename should reflect your IP.

DNS servers setup…

Ok, now that we got this set up, we need to tell our system to use the local DNS server before going for the ISP and beyond. To achieve this, use Networking manager in Ubuntu, here’s how mine looks like. The final goal is for the /etc/resolv.conf too read: nameserver 127.0.0.1.

…and finishing up

Now that everything is set up, restart bind:

sudo /etc/init.d/bind9 restart

Test your setup by pinging anything.dev. If you get the response from your server, all is working great.

Apache Virtual Document Root

If your projects have similar / identical directory structure (i.e. public directory for publicly available files) than you can go a step further and setup the Apache Virtual Document Root. In doing so, you will be able to create a new directory in your projects root and have it magically turned up by calling http://newdirectory.dev.

<IfModule vhost_alias_module>
    <VirtualHost *>
        UseCanonicalName Off
        VirtualDocumentRoot "/path/to/projects/%1/public"

        ServerName projects.dev
        ServerAlias *.dev

        SetEnv APPLICATION_ENV development
    </VirtualHost>
</IfModule>

# Enable mod_vhost_alias apache module
sudo a2enmod vhost_alias
# Restart server
sudo /etc/init.d/apache2 restart

I don’t have this enabled for myself, but it does work, although not well tested. For further info on this topic, check the following links:

P.S. Yes, I got carried away while creating the featured image :)

Comment driven development

There is quite a handful of programming techniques out there; TDD, BDD, YAGNI, DRY to name a few. This post will be about something many people might already be doing but don’t know it has a name: Comment-driven development or comment programming.

CDD is helpful for:

  • prototyping,
  • spitting out your thoughts in code editor, so you don’t forget anything later (good for brainstorming sessions),
  • explaining what needs to be done if someone else is going to be writing the code itself,
  • commenting the code :). Comments could remain, so your code is documented from the get-go

I often start the new PHP file or class or even method with the layout in comments. Here’s an example:

// Get the needed models
// Collect todo items
// Get lists that the todo items belong to
// Send to View

Ok, everything is clear. After the real code sets in it looks like this:

public function someAction()
{
    // Get the needed models
    $todoTable  = new TodoTable();
    $listTable  = new ListTable();
 
    // Collect todo items
    $todos      = $todoTable->findByAuthor($author);
 
    // Get lists that the todo items belong to
    foreach ($todos as &$todo) {
        $todo['lists'] = $listTable->find($todo['list_id']);
    }
 
    // Send to View
    DIC::get('View')->todos = $todos;
}

As you can see, the comments can stay in place. Even for this simple example, it is good practice to document your code.

The Wikipedia article states:

In comment programming the comment tags are not used to describe what a certain piece of code is doing, but rather to stop some parts of the code from being executed. The aim is to have the commented code at the developer’s disposal at any time he might need it.

And later on:

However, comment programming is used instead of a real implementation. The idea is that many functions can be written like this, and then the design can be reworked and revisited without having to refactor a lot of source code.

So, Wikipedia article is somewhat contradictory to itself. The aspect of comment programming I am writing about here is the “comments instead of a real implementation” part.

Do you write your code with comments first approach? Do you use some other technique?

Test projects viewer

I have a couple of test projects in my test directory. This is where I usually put the latest wordpress, phpBB or any other script or web software I would like to test out or develop and play with. Until recently I had to access those by writing the virtual host path (www.test.local) and then append the directory name (in.eg. /drupal). I got tired of it, and coded a nifty little “browser” which displays all of the directories and files. Combined with the DNS wildcards, you can have unlimited virtual domains without having to configure them in vhosts, setting the /etc/hosts and restarting apache server. I have included this in the zip file found at the end of this post.

We are using bind dns server to resolve everything that comes to the “test” domain to your machines IP address. After that, Apache takes care of the rest. And what he does is kinda cool. The .htaccess file has a set of rules to test weather the index.php exists in the requested directory (via subdomain), and if it does, he redirects us to that directory. If the index.php doesn’t exist, our “main” index.php shows the contents of that directory, so you can select any other file and run it. Let’s start.

Continue reading “Test projects viewer” »

PHP and template engines (and some other stuff)

I’m developing web sites for quite some time now, started when i was… Young? Yellow? Well, started a long time a go in a galaxy… AARGH! Can’t get Star Wars out of my life! Anyway. In the beginning i was using the good old php mess approach:

echo 'ul';
foreach($array as $item) {
    echo '<li>Some $item here</li>';
}
echo '<ul>';

And so on. For onepagers this was enough. So i stumbled accross mambo (former Joomla) and saw the raw power of cms and, well for me, good coding. K, let’s make ourselves a content management system. But how? What do we need? The neccesary ingridients where these:

  • Apache with php (obvious)
  • MySQL database (oh, what’s this database thing for?)
  • foresight

What’s the most important? No, wrong, not coffee. Foresight! Without analyzing and planning the outcome can’t be good. I started to code. Heavily. Took a good number of different approaches, all ended bit dull and like they couldn’t take on serious tasks.

Continue reading “PHP and template engines (and some other stuff)” »