Wern Ancheta

Adventures in Web Development.

Plans for 2015

| Comments

Its 2015 and I think the best way to start one’s year right is to lay out some plans. This 2015 I want to be more ambitious with the side projects that I do, I want to make my head hurt a little more. Because that’s the only way to grow as a developer. I also want to read more books, watch more video courses and write more this 2015.

Side Projects

  • Anime API – I’m a really big fan of anime. I watch anime everyday. That’s why I’m thinking of creating an API about anime. It will be something like IMDb but for anime. It will include information such as the title, genre, cover image, plot, air dates, and links to relevant websites.
  • Pokemon API – Pokemon is one of the things I grew up with. Starting from the Red Version on Gameboy Color up to the Pokemon X Version on 3DS. There’s already an existing Pokemon API which is really good, except the fact that its lacking some data. Specifically on base stats, in-game trainers, type defenses, moves learned and pokedex entries. I want an API which has all of the information you need to know about Pokemon.
  • Antares – At the later part of 2014 I published this app on google play. Its a news reader for developers. Currently its only getting news from various newsletters that I subscribe to, hacker news, medium, readability and other developer websites. I’m planning to add machine learning capabilities to it so it will only recommend links that are more interesting to the current user.
  • Ahead – As I’ve introduced before, ahead is an app for scheduling posts to be published later to twitter, facebook or linkedin. I’m thinking of adding integration to delicious, readability or instapaper. Or maybe get some data from the antares api and have it recommend some links for the user to share.
  • vid-master – This is a project I started 5 months ago in the company that I’m currently working for. Its a laravel app for creating video websites, this allows the user to import videos from youtube or vimeo and then use those as the content for the video website. Unfortunately this got abandoned so I asked my boss if I could just open-source it. And he agreed, that’s why its now on my Github waiting for updates.

Those are my ideas for now. I’ve already mentioned some of the projects that I’m planning to do in my brain dump post.

Code Quality

As developers were in a constant pressure of releasing stuff out in the open. And that is true for me as well. Most of the time I sacrifice quality for the sake of speed. So that I can release things fast. That is why this 2015 I’ll try to write more quality code whenever possible. I won’t proceed with the first solution that comes to mind because that’s often the hacky solution which results in dirty code. I’ll also try to learn about design patterns, inversion of control, dependency injection, and leverage existing libraries more.

Articles

Aside from the ones I already mentioned on brain dump. I’m thinking of doing the following as well:

  • Laravel Series – as I’m mainly using laravel for most of my projects I think its necessary for me to write about it to further enforce what I’ve learned and to share it to others.

Screencast

I had this plan for many years now but I never really got to put it into action. Hopefully this year I will get to create a new youtube channel such as thenewboston or phpacademy to share the things that I’ve learned by means of a video. I think I really need this to exercise my verbal communication skills because as a remote and sole developer I don’t really need to talk that much to do my job.

Health

Two years ago I wrote this blog post on how to stay healthy as a developer. As you might already know being a developer or any other job that requires you to sit all day long is bad for the health. That’s why this 2015 I want to be a healthier person by means of walking. Walking is a very good physical activity that requires less effort. I recently bought a fitbit flex which allows me to track the number of steps I’ve made and the calories I’ve burned. Hopefully this will help me to walk more and keep me motivated.

Time Management

I watch a lot of anime (6 to 14 titles per season), I waste a lot of time reading articles that I think matters, I like to keep up with a lot of things which ends up consuming most of my free time (Twitter, Facebook, Hacker News, Podcasts). This 2015 I want to be more picky about the things I watch and read so that I can have more time to do what’s really important.

I think that pretty much sums it up. Looking forward for a productive and bountiful 2015.

Why I Code

| Comments

Why I code? I’ve been thinking about this lately. Why is it that I love coding? What is it about coding that keeps me from doing it? What makes it so special? How do I maintain my love for coding even if its so frustrating most of the time. When I was younger I was into drawing. Cartoon characters, robots, sceneries, abstract art, and anything else that picked my interest. Not a week would past that I haven’t added a new drawing in my collection. What kept me drawing back then was the sheer joy of adding a new drawing in my collection. It was sort of addictive. I couldn’t wait to fill that old magazine with my drawings. In the end I ended up filling up about 8 old magazines with about 50 drawings each. Why did I stopped? It was around college days that I stopped drawing entirely. Mainly because of how busy it was and I really wanted to concentrate on my studies. College was my very first introduction to coding. The first programming language that I’ve learned was c++. I easily picked up coding at first because we were just assigning variables and outputting strings. But as we dive deeper into adding actual logic in the programs that we wrote in our class, that’s when my head started to hurt. I remember spending about 3 hours on our first project without making any progress. That was the dark ages when I didn’t know how to ask Google for answers. Back then I never thought I’d be doing coding as a primary source of work. I thought it was too difficult. Maybe I’ll just do animation and stuff. But hey, Computer Programming was a major subject that I needed to pass. So it just came naturally that I needed to do something about it. That was when I started to take some of my free time and use it to practice writing some code. I took some of the exercises that we were having and tried to write it from scratch without looking at any of the notes. Once I’ve successfully implemented it, I added some features. That was also when my Googling skills started to improve, as I needed some useful answers to the problems that I was having. Then I also discovered something that will change my life forever. Stackoverflow. I joined Stackoverflow in hopes that it will provide me some answers to the problems that I was having. Before I knew it, I have already asked about a hundred questions. Most of them with some useful answers from the community. Some were marked as a duplicate question, some were marked as non-useful or out of scope. Either way the comments and answers were really useful. Sometimes even the comments are enough.

Over time I got better at coding. I started to feel confident about my coding skills. I started believing that I could actually do this for a job. As I started to know more about programming and gain more experience. I realized just how much I still don’t know. That’s the time when I started my very first blog which I would write about some of the things that I’ve learned in my coding adventures. At first I was writing about some VB.Net CRUD things. Because that was what they were teaching at school. I also wrote about some Java stuff when it was taught. Then came Web Development. HTML, CSS, JavaScript, PHP and MySQL. And I taught to myself. Dude! this is pretty sweet! I could write a program and have it used by many people as long as they’re connected to the internet. That’s when we were introduced to w3schools and htmlgoodies. These websites quickly became my best friend. They were my number one source of web stuff for a long time. But then came w3fools. Which made me realize that w3schools actually sucks. I started using MDN as my primary reference for web stuff as w3fools recommended.

Fast-forward to the present. I am now calling myself a web developer. Specifically a full-stack developer. Responsible for almost everything that’s needed to release a whole website out in the open. I’m a web developer for about 2 years now. Mainly doing some remote work. And sometimes freelancing on the side. And that leads us to the original question. Why I code? That’s mainly because it gives you the ability to reach thousands of people and make their lives easier through the use of the app that you’ve written. Its the joy of creating something out of nothing. The challenges that you encounter as you try to build your app. That rewarding feeling that you get when you finally implemented that feature which made your brain explode. Or that feeling that you got when you finally solved that bug that’s been haunting you for 10 hours. Its also about the excitement that you feel whenever there’s a shiny new toy that comes out. The shiny new toy can be any library, framework or programming language that was released recently. Finally, I code because I want to leave something to the world that will prove my existence. That I have onced lived and created this useful website or app that has been useful to many people. I’m still far from that realization though. Like I said earlier, my side projects mainly solve a specific problem that I’m having. And the projects that I’m getting from the company I’m currently working for are targeted only for a specific group of people and country. At most there will only be hundreds of people who will be able to use it.

Year-End Review

| Comments

This has been a very good and productive year. Lots of articles written, podcasts listened to, articles and books read, company and client projects, side-projects, travels, video games played, anime series and movies, video tutorials and talks watched. In this blog post I’ll try to recollect some of those.

Articles Written

I’m not going to list out every article I’ve written on this blog for this year. We have the archives for that. So here are the articles that I consider the best from 2014. These are based from the number of responses I got from both the commenting system and social media:

I have also started writing for Sitepoint’s PHP Channel this year. Here are some of the articles I’ve written:

If you want to check out some of my other articles on Sitepoint, please visit my author page.

Podcasts Listened To

Articles Read

There’s a gazillion of them. To give you an idea how much I articles I’ve read this year, here’s a screenshot of session buddy, a chrome extension that I’m using for saving sets of tabs.

sessions

Books Read

Ok I was kidding when I said I read lots of books this year. Actually I finished one. That is Thinking Fast and Slow by Daniel Kahneman. I tend to read 2 to 3 books at a time, so I’m halfway through This Will Make You Smarter: New Scientific Concepts to Improve Your Thinking by John Brockman. And recently I’ve started reading Optimism Bias by Tali Sharot.

Company and Client Projects

I’m really thankful for having a great boss who always gives me some nice and cool projects to work on. This year I worked on a total of 7 company projects. 1 of those was from the previous company that I worked for. I joined my current company in late March this year so there’s that 1 leftover project. Here are some of the company projects that I’m most proud of:

As for the client project, I don’t actively look for them and even if I get one, I usually reject it because of lack of experience on the technologies to be used and overall lack of interest. There’s only one project that got through the tight screening, and that is the ebay store automator.

Side-projects

There’s an abundance of side-projects this year. I usually do these projects to automate some of the tasks that I usually do by hand, or to get my hands dirty on a specific technology I’ve never worked with before. Here are some of those:

Travels

I recently got a car so I naturally got exposed more exposure to the outside world as an excuse for getting some driving experience. Here are some of the places I’ve been to this year. I’ve mostly visited towns inside the same province where I live:

  • Botanical Garden, San Fernando City, La Union
  • Intake Dam, Sudipen, La Union
  • Bahay na Bato, Luna, La Union
  • Occalong Falls, Luna, La Union
  • Callao Caves, Penablanca, Cagayan
  • Aparri, Cagayan
  • Basilica Minore of Our Lady of Piat, Piat, Cagayan
  • Baluarte, Vigan City, Ilocos Sur
  • Pindangan Ruins, San Fernando City, La Union
  • Pugo Adventure, Pugo, La Union
  • Basilica Minore of Our Lady of Charity, Agoo, La Union
  • Namacpacan Church, Luna, La Union
  • Balay Anito Falls, Santol, La Union

Video Games

Not really a lot. I just played a bunch of Pokemon on my Nintendo DS Lite. These days I barely even touch it since I’ve already finished all the Pokemon games available for DS. That’s why I’m planning on selling it to buy the 3DS which apparently have some pretty badass Pokemon Games in Full 3D.

Anime Series

I’m a big anime fan, and I’m probably watching more than what I should be watching. At most around 40 anime series per year. But here are the only ones that I can recommend:

  • Parasyte
  • Hamatora
  • Haikyu
  • Amagi Brilliant Park
  • Hunter x Hunter (2011 Remake)
  • Free!
  • Noragami
  • Terra Formars
  • Nanatsu no Taizai
  • Yowamushi Pedal
  • Tokyo Ghoul
  • Shingeki no Bahamut
  • Garo: The Animation
  • Terror in Resonance
  • Captain Earth
  • Log Horizon
  • Sword Art Online (Season 2)
  • Chunibyo
  • Chaika – The Coffin Princess
  • World Trigger
  • Barakamon
  • Brynhildr in the Darkness
  • Kagerou Project
  • Psycho Pass (Season 2)
  • Aldnoah.Zero
  • Akatsuki no Yona
  • Akame Ga Kill

Movies

Lots of good movies this year but here’s the best:

  • Dawn of the Planet of the Apes
  • Captain America: Winter Soldier
  • X-men: Days of Future Past
  • Lucy
  • Divergent
  • Cloverfield

Talks

I don’t really go to conferences so I only watched talks from all over the world via Youtube. I’ve watched a lot of them this year but I’ll only pick this one talk:

Brain Dump 0

| Comments

Welcome to the first issue of brain dump. Brain dump is my attempt on putting the things that are always at the back of my mind into writing. Everything has its limits, and that includes the brain. Brain dump is my way of freeing up some space in my brain in hopes that I can use it on something else.

Things I want to learn

  • Meteor.js
  • Design Patterns in PHP and JavaScript
  • Behavior Driven Development in PHP: Codeception
  • JavaScript Unit Testing
  • PostgreSQL
  • Ember.js
  • Python
  • Django
  • Ruby
  • Ruby on Rails
  • SEO
  • Web Semantics
  • How to program Arduino or Raspberry Pi
  • ARIA
  • Canvas
  • SVG
  • Agile Development
  • Unit Testing
  • Regression Testing

Books I want to read

  • How to Win Friends and Influence People
  • Strangers to Ourselves
  • The Willpower Instinct: How Self-Control Works
  • You Are Not So Smart
  • Sway: The Irresistible Pull of Irrational Behavior
  • Mindfulness
  • The Optimism Bias
  • The Social Animal
  • The Honest Truth About Dishonesty: How We Lie to Everyone
  • Yes! (50 Scientifically Proven Ways to be Persuasive)
  • The Design of Everyday Things
  • The Paradox of Choice: Why More is Less
  • The Compass of Pleasure
  • The Lucifer Effect: Understanding How Good People Turn Evil
  • The Pragmatic Programmer
  • Clean Code
  • Predictably Irrational
  • Social Engineer: The Art of Human Hacking
  • Made to Stick: Why Some Ideas Survive and Others Die
  • Head First Design Patterns
  • Refactoring – Improving the design of existing code
  • The Passionate Programmer
  • Ship it!
  • What Makes Your Brain Happy (and Why You Should Do the Opposite)
  • Don’t Make Me Think
  • Incognito: The Secret Lives of the Brain
  • The Power of Habit (Why We Do What We Do)
  • The Productive Programmer
  • The Art of Choosing
  • Mistakes Were Made (But Not By Me)
  • Priceless
  • Switch: How to Change Things When Change is Hard
  • Writing Solid Code
  • Practices of an Agile Developer
  • Stumbling on Happiness
  • Man’s Search for Meaning

Video Courses I want to watch

  • Codeschool – JavaScript Best Practices
  • Codeschool – Mastering Github
  • Codeschool – Design Fundamentals
  • Udemy – Life’s Little Secrets
  • Udemy – Improve Your Mental Well Being
  • Udemy – Freelance Jumpstart
  • Udemy – Sauce of Great Writing
  • Udemy – Become a Super learner
  • Tutsplus – Automated Testing with PHP
  • Tutsplus – Artisan Commands and You
  • Tutsplus- Custom Interactive Maps with Google Maps API
  • Tutsplus – Canvas Essentials
  • Tutsplus – SVG for Web Design
  • Tutsplus – Django Unchained
  • Tutsplus – SVG Uncovered
  • Lynda – Web Semantics

Projects I want to build

  • Wordpress Donations Plugin – can accept bitcoins, paypal, stripe
  • Newsletter Subscription for Octopress – using Mailchimp API
  • Gilium – similar to hacker news reader; mobile app for aggregating and suggesting content
  • Dropshipster – a web application for easy dropshipping
  • Vacationr – vacation planner app + social network

Things I want to write

  • My web development workflow
  • My mobile development workflow
  • Getting Started Guides
    • Yahoo Finance API
    • Ionic
    • Shopify Theme Development
    • Twilio
    • Youtube API
    • Vimeo API
    • Facebook API
    • Twitter API
    • Linkedin API
    • Stripe API
  • A Whirlwind Tour of Web Developer Tools
    • Linting
    • Testing
    • Pre-processors
    • Coding Standards
    • Boilerplates and Front-end frameworks
    • Templating
    • Deployment
    • Miscellaneous – tools not mentioned in any of the above, but still useful

Articles I want to read

There’s bazzilion of them. It would take forever to write it here.

Getting Started With RabbitMQ in PHP

| Comments

This article was originally published at Binpress:
http://www.binpress.com/tutorial/getting-started-with-rabbitmq-in-php/164

In this tutorial I’m going to walk you through how you can use RabbitMQ in PHP. But first what is RabbitMQ? RabbitMQ is a message broker software. It acts as a middleman between a producer and a consumer. Producer being the data that we want to pass, and consumer being the entity that we want to pass it to. RabbitMQ uses a queue, you can think of it as a mailbox where you drop your letters. RabbitMQ then takes the letters and delivers it to its destination.

Installing RabbitMQ

In Ubuntu and other debian based operating system you can install RabbitMQ by executing the following commands from your terminal:

1
2
3
4
5
6
7
8
echo "deb http://www.rabbitmq.com/debian/ testing main"  | sudo tee  /etc/apt/sources.list.d/rabbitmq.list > /dev/null
sudo wget http://www.rabbitmq.com/rabbitmq-signing-key-public.asc
sudo apt-key add rabbitmq-signing-key-public.asc
sudo apt-get update
sudo apt-get install rabbitmq-server -y
sudo service rabbitmq-server start
sudo rabbitmq-plugins enable rabbitmq_management
sudo service rabbitmq-server restart

What the first command does is to append the rabbitmq source to the software sources list. Next we download the rabbitmq signing key using wget. Then add the key to Ubuntu. Next we call apt-get update to update the software sources list. Next we install the RabbitMQ server, start it then enable RabbitMQ management plugin. This provides an HTTP-based API management for monitoring your RabbitMQ server. Finally we restart the RabbitMQ server so that changes will take effect. The default username and password is guest. And the default port in which it runs is 5672.

If you’re on another operating system, you can find how to install RabbitMQ for your specific operating system here: Downloading and Installing RabbitMQ.

Working with RabbitMQ

Once you’re done installing RabbitMQ, we can now install the AMQP library for PHP. This implements the AMQP (Advanced Messaging Queue Protocol) protocol. As the name suggests it is a protocol used for messaging. Start by creating a new directory, this is where we will put all the files for testing RabbitMQ. Next create a composer.json file and add the following:

1
2
3
4
5
{
  "require": {
      "videlalvaro/php-amqplib": "2.2.*"
  }
}

Next, open up your terminal and cd into the directory you created earlier then execute composer install to install the AMQP library.

Before we move on, lets also install Swiftmailer. You can do that by executing the following command from your terminal. This also adds an entry to Swiftmailer to your composer.json:

1
composer require swiftmailer/swiftmailer @stable

We will be using Swiftmailer for the sample app that were going to create. What we will do is create an app that will send emails for our users. Normally emails takes a few seconds before it is sent, adding an attachment to the email also adds to that time. In the real world we don’t really want our users to wait. What we want to do is make them believe that we have already sent the email for them by outputting to the screen that their message has been sent. This is where RabbitMQ comes in. We will use it as some sort of a mailbox in which multiple users can just drop their messages in. RabbitMQ will then take care of sending the messages in the background.

Sending Messages

First lets create the form to be used for sending emails. This will accept the name and email address of the sender, the email address of the receiver and then the subject and message. Name the file form.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
if(!empty($_GET['sent'])){
?>
<div>
    Your message was sent!
</div>
<?php
}
?>
<form action="mailer.php" method="POST">
    <div>
        <label for="from">From</label>
        <input type="text" name="from" id="from">
    </div>
    <div>
        <label for="from_email">From Email</label>
        <input type="text" name="from_email" id="from_email">
    </div>
    <div>
        <label for="to_email">To Email</label>
        <input type="text" name="to_email" id="to_email">
    </div>
    <div>
        <label for="subject">Subject</label>
        <input type="text" name="subject" id="subject">
    </div>
    <div>
        <label for="message">Message</label>
        <textarea name="message" id="message" cols="30" rows="10"></textarea>
    </div>
    <div>
        <button type="submit">Send</button>
    </div>
</form>

Next, create the file which will push the message into the queue. Name the file sender.php. Require the autoload.php file so that our dependencies will be automatically loaded by PHP. Then use the AMQPConnection and AMQPMessage from the AMQP library. AMQPConnection allows us to create a new connection to the RabbitMQ server and AMQPMessage allows us to create messages that we can push to the queue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPConnection;
use PhpAmqpLib\Message\AMQPMessage;

$connection = new AMQPConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();

$channel->queue_declare('email_queue', false, false, false, false);

$data = json_encode($_POST);

$msg = new AMQPMessage($data, array('delivery_mode' => 2));
$channel->basic_publish($msg, '', 'email_queue');

header('Location: form.php?sent=true');
?>

Breaking it down, first we create a new connection by creating a new instance of the AMQPConnection class. This requires the following arguments:

  • host – the host in which the RabbitMQ server is running. In this case we’ve installed RabbitMQ on the same computer we are running the script in. So it should be localhost. Note that in the real world we install RabbitMQ on a another server, different from the one were using to serve our websites. So instead of localhost we use the public ip address of that server.
  • port – the port in which the RabbitMQ server is running.
  • user – the username to use for logging in to the server. By default the username is set to guest.
  • password – the password of the user. By default the password is set to guest.

Next we create a channel. We can do that by calling the channel() method from the connection that we have just declared.

1
2
3
<?php
$channel = $connection->channel();
?>

Next we declare the queue to be used by calling the queue_declare method.

1
2
3
<?php
$channel->queue_declare('email_queue', false, false, false, false);
?>

The queue_declare method takes up the following arguments:

  • queue name – a name that you want to use for the queue, you can supply anything for this.
  • passive – a boolean value for specifying whether to check for an existing exchange.
  • durable – a boolean value for specifying whether the RabbitMQ holds on to a queue when the server crashes.
  • exclusive – a boolean value for specifying whether the queue is used by only one connection.
  • auto-delete – a boolean value for specifying whether the queue is deleted when the last subscriber unsubscribes.

Next we convert the POST data that we receive from the form to a JSON string. We can only pass strings as a message so we’ll have to convert this later on into an array on the receiver’s end.

1
2
3
<?php
$data = json_encode($_POST);
?>

Next we create a new message. This accepts 2 arguments: the data and an array of options. For the array of options we specify the delivery_mode to 2 which means that the message is persistent. This means that it isn’t lost when the server crashes or an error occurs.

1
2
3
<?php
$msg = new AMQPMessage($data, array('delivery_mode' => 2));
?>

Next we publish the message by calling the basic_publish() method on the channel. This accepts 3 arguments: the message, the exchange and the name of the queue. If you’re wondering why we set the value of exchange to an empty string, that’s because we don’t really need it. The exchange is commonly used for pub-sub patterns. What were using here is just basic publish.

1
2
3
<?php
$channel->basic_publish($msg, '', 'email_queue');
?>

Finally we just redirect the user to the form.

1
2
3
<?php
header('Location: form.php?sent=true');
?>

Receiving Messages

Now were ready to write the code that will receive the messages sent by users. Name the file receiver.php. Here’s the full contents of the file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPConnection;

$connection = new AMQPConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();

$channel->queue_declare('email_queue', false, false, false, false);

echo ' * Waiting for messages. To exit press CTRL+C', "\n";

$callback = function($msg){

    echo " * Message received", "\n";
    $data = json_decode($msg->body, true);

    $from = $data['from'];
    $from_email = $data['from_email'];
    $to_email = $data['to_email'];
    $subject = $data['subject'];
    $message = $data['message'];

    $transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
      ->setUsername('YOUR_GMAIL_EMAIL')
      ->setPassword('YOUR_GMAIL_PASSWORD');

    $mailer = Swift_Mailer::newInstance($transporter);

    $message = Swift_Message::newInstance($transporter)
        ->setSubject($subject)
        ->setFrom(array($from_email => $from))
        ->setTo(array($to_email))
        ->setBody($message);

    $mailer->send($message);

    echo " * Message was sent", "\n";
    $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
};

$channel->basic_qos(null, 1, null);
$channel->basic_consume('email_queue', '', false, false, false, false, $callback);

while(count($channel->callbacks)) {
    $channel->wait();
}
?>

Breaking it down, the first 5 lines of code are basically the same as the one we have on the sender.php file. Then we just output a message saying how we can stop the file from running. We need to run this file from the terminal so to stop it we just hit CTRL + C.

Next we declare a named function. This will be used for processing the message that we passed from the sender. The first thing it does is output that the message was received. Then we use json_decode() to convert the JSON string back to an array.

1
2
3
4
5
6
<?php
$callback = function($msg){
    echo " * Message received", "\n";
    $data = json_decode($msg->body, true);
};
?>

Next we extract the data and assign them to each of their own variables:

1
2
3
4
5
6
7
<?php
$from = $data['from'];
$from_email = $data['from_email'];
$to_email = $data['to_email'];
$subject = $data['subject'];
$message = $data['message'];
?>

Next we declare a new transporter to be used by Swiftmailer. This allows us to use a gmail account for sending emails. Declaring a new instance accepts 3 arguments: the host, port and the encryption. Then we set the username and password.

1
2
3
4
5
<?php
$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
      ->setUsername('YOUR_GMAIL_EMAIL')
      ->setPassword('YOUR_GMAIL_PASSWORD');
?>

Next we declare a new mailer instance, and supplying the transporter as an argument.

1
2
3
<?php
$mailer = Swift_Mailer::newInstance($transporter);
?>

Next create a new message, this also takes up the transporter as its argument. We then set the subject, from field, to field, and body of the message.

1
2
3
4
5
6
7
<?php
$message = Swift_Message::newInstance($transporter)
        ->setSubject($subject)
        ->setFrom(array($from_email => $from))
        ->setTo(array($to_email))
        ->setBody($message);
?>

Finally we send the message and output that the message was sent. The last line basically tells RabbitMQ that the sending of the message has indeed been successful.

1
2
3
4
5
6
<?php
$mailer->send($message);
echo " * Message was sent", "\n";

$msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
?>

Running the program

You can now run the receiver by going to your terminal and executing the following command:

1
php receiver.php

Once its running, go to your browser and access the sender.php file. Enter the details of your message and click on send. You’re instantly greeted by a ‘Your message was sent!’ text but if you immediately check your email account its not there yet. If its not there then the queue is still processing it. Check the output displayed on the terminal window where you executed the receiver. You should see a ‘Message was sent’ output if the email was already sent.

Conclusion

RabbitMQ is a nice way for implementing messaging applications such as the one we created in this tutorial. We have barely scratch the surface with this tutorial. I recommend you check out the getting started guides and the documentation to learn more.

Christmas Wishlist 2014

| Comments

13-inch MacBook Pro with Retina display

macbook pro

I have always wanted a Macbook Pro since birth. But due to its priciness I never got myself to buy one.

I’d like to stick with the following hardware:

  • Processor: 3.0GHz Dual-core Intel Core i7
  • Memory: 8GB 1600MHz DDR3L SDRAM
  • Storage: 512GB PCIe-based Flash Storage

Google Nexus 5

Google Nexus 5

Not really a Google fanboy, I’m just more curious about a smartphone made by Google rather than an Apple’s iPhone or Samsung’s Galaxy.

PS Vita

sony ps vita

I’ve always been a fan of game consoles from Sony and their games are really good. Here are just some of the titles that I’ve enjoyed playing on their PSP game console:

  • Patapon – that’s Patapon 1, 2 and 3
  • God Eater
  • Final Fantasy VII: Crisis Core
  • Harvest Moon – boy & girl, innocent life and hero of the leaf valley
  • Ratchet and Clank
  • Naruto Ultimate Ninja Heroes – that’s 1, 2 and 3
  • GTA: Vice City
  • Ratchet and Clank
  • Secret Agent Clank
  • Valhalla Knights

Nintendo 3ds

Nintendo 3ds

To be honest I only really want this game console because of Pokemon. Nintendo 3ds have revolutionize the Pokemon gameplay in this console. There’s a bunch of new stuff, and the best thing is that its 3D. So the Pokemon games created for this console won’t really look like the Pokemon games created for Nintendo DS or Gameboy.

Fitbit Flex

Fitbit

Fitbit is an all-in-one tracker for the body. With it you can do the following:

  • track steps, distance and calories burned
  • monitor how long and well you sleep
  • silent wake alarm
  • logs food consumption, weight changes

Bose QuietComfort 25

Bose Noise Cancelling Headphones

I’ve always wanted a noise cancelling headphones that I can use while working. Based on my research Bose is the best thing out there.

Olympus ME-52W Noise Canceling Microphone

olympus microphone

Screencasting has always been on my TODO list. As a developer I wanted to create a Youtube Channel where I record screencasts of things I’ve learned. The only thing that’s stopping me is the not-so-quality sound recorder that comes with my laptop.

Seagate Backup Plus 5TB Desktop External Hard Drive

seagate external hard drive

Last thing on this list is this 5TB External Hard Drive from Seagate. I download a lot of stuff from the internet to prepare for events where there is no internet and I have nothing to do on my computer.

Always Scratch Your Developer Itch

| Comments

As developers, no matter how busy we are with our lives, its important for us to always scratch our developer itches every now and then. What I mean by itches are the things that you want to do as a developer. Be it working on a side-project that you’ve been wanting to do for months, playing with a new technology, library or a programming language. Or reading an in-depth article about a new programming technique. Or watching a video tutorial about a framework that you’ve been wanting to learn. Or watching recorded talks from developer conferences all over the world. Or writing an article about a cool technique you’ve discovered recently. And other things that you always have at the back of your mind but never really got to do because of lack of time.

Lack of time is always the reason we give to ourselves. But time is not really the problem. We can always make time for something if we really love to do it. Yes we also have lives to live. But we also need to give priority to the things that matter to us as a developer. As a developers, we have the responsibility for continuous learning. To improve our craft for the better. And this is what it means to scratch your developer itch. If you have it, you’ll always find time to scratch it no matter how busy you may be.

On the contrary, we also have lives to live. Nothing is more important than our families and our lives as actual people. So giving time to that is our priority as a human being. After all life is not all about work. Life is about living it in the best way possible. And that is through spending quality time with our loved one’s.

In conclusion, its really all about balance. If you can’t find time every weekend to scratch your own developer itch, then maybe do it once or twice a month. Maybe 4-8 hours twice a month doing a side project is a good start. You can also go to work early and read up on blogs before and after the alloted time for work. Listen to podcasts while commuting. Most podcasts provide download links to each episode which you can save into your mp3 player of smartphone. Watching a 5-minute video tutorial just before going to bed. Every bit of time counts. It doesn’t matter how little or how much, what’s important is to give time to scratch our developer itches whenever we can. If you do, you’ll be a happier developer. Its like the feeling you get when you were finally able to get what you’ve been wanting to buy for a long time.

On Sleep

| Comments

As developers we tend to not give much priority to sleep. Most of the time its due to a lot of responsibilities: work, family, and side-projects. And oftentimes we even bring in our todo list in our mind when we go to bed. As a developer myself, I tend to get less sleep than what’s required. Sometimes not enough to fully function and be productive during the day. In this blog post I’m going to share some of the things I’ve learned about sleep.

Stages of Sleep

There are actually stages to sleep, its not just being awake or asleep. It is important that we understand this concept because its the core of what sleep is all about.

  1. Stage 1 – also called light sleep. This is where we drift in and out of sleep.
  2. Stage 2 – heart rate slows down and body temperature starts decreasing in preparation for deep sleep.
  3. Stage 3 – breathing becomes slower, blood pressure begins to drop, muscles becomes relaxed, cell growth and restoration occurs.
  4. Stage 4 – slow brain waves are produced.
  5. REM – Rapid Eye Movement sleep. This is where dreams usually occur. The body becomes immobile. Energy is provided to the brain and body.

Factors Affecting Sleep

There are 5 factors which affects sleep:

  • Light
  • Consistency
  • Activeness
  • Environment
  • Consumption

Light

Light affects the production of melatonin, a sleep hormone. Ample exposure to light during the day, and minimal exposure during the night 1-2 hours before sleep is recommended. The best light source is sunlight in the morning around 6-8 AM. For rainy days you can use light boxes. The main idea is that exposure to light helps produce serotonin, a neurotransmitter which affects sleep.

Earlier I’ve said that light exposure should be minimized during the night. But we haven’t really defined what light is. Light is not just the fluorescent light, its also the light which is emmitted by electronic devices such as laptops, tablets and smartphones. And if its not already obvious, the light which comes from a television is also light. As a developer I want to maximize the amount of time I spend doing something productive. And that almost always means staring at the computer screen until I actually go to bed. This is not good for sleep as it decreases melatonin production. A good alternative is to install flux. What it does is adjust the color temperature to adapt to the time of the day. This effectively reduces the bluelight which is bad for sleep. If you’re using a tablet or smartphone at night, simply look for similar apps. Blue light filter is a good one for android phones.

Consistency

Our bodies love consistency. The idea is that you should always sleep and wake at the same time. Our bodies have something like an internal clock. And if you’re consistent with your sleep schedule, you almost always wake up or feel sleepy at the same time of the day. You wouldn’t even need an alarm clock to wake you up if you’re consistent.

Activeness

Regular exercise is important. As developers, were basically one of the people with the most sedentary job. Our brains and fingers are the only part of the body that is moving. So to get good sleep we must make it a habit to have exercise of around 20-30 minutes a day. Quality sleep is all about temperature oscillation. The idea is that the higher the temperature our body reaches during the day, the lower it gets during the night. And the lower the temperature means more deep sleep. Take note that exercise a few hours before sleep is bad as it makes you active. Personally I prefer exercising in the morning as it completely removes the possibility of exercising too near before bed time. And it hits 2 birds with one stone, as I also get some morning sunlight while exercising. Jogging, cycling and running are good types of exercise.

Environment

The environment also affects sleep. The temperature should neither be too hot or too cold. Around 18-23 degree celsius is a good baseline. Turning on the AC is also good. It effectively lowers the room temperature and also blocks out outside noises because of its white noise. Its a no-brainer that to get quality sleep you must always sleep somewhere where you’re comfortable. Sleeping position affects the quality of sleep as well, the general rule is to always sleep in a position in which you are comfortable. But its always a good idea to avoid sleeping on your stomach, as it reduces the amount of oxygen that goes to your lungs.

Consumption

What we eat affects our sleep as well. Here are some foods which is good and bad for sleep.

Foods to consume
  • Cherries
  • Milk
  • Jasmine Rice
  • Banana
  • Sweet Potato
  • Turkey
  • Valerian Tea
  • Walnuts
  • Almonds
  • Cheese and Crackers
  • Lettuce
  • Tuna
  • Garlic
  • Chamomile Tea
  • Honey
  • Shrimp

Basically anything else which can help produce melatonin. Or foods which has sedative properties or natural muscle relaxant.

Foods to avoid
  • Alcohol
  • Fat
  • Dark Chocolate
  • Coffee
  • Soda
  • Spices
  • Chicken
  • Celery
  • Ice Cream

Avoid anything that is high on fat content or caffeine. Its best if you can avoid caffeine entirely as it stays on your body for long periods of time once consumed. Also avoid diuretics, a subtance which promotes the production of urine.

The general consumption rule is don’t eat too close to bed time. Eating around 2-4 hours before sleep is a good idea. 2 hours for light meals, 4 hours for heavy meals (dinner buffet). Another important thing is to stay hydrated, 8-10 glasses (8 ounces) of water is recommended. You can definitely consume more if you’re an athletic type or you sweat a lot. Always remember to not drink too much near bed time to avoid waking up to go to the bathroom. As a rule, avoid drinking too much water 1-2 hours before sleep. You can consume in small amounts (half a glass) if you want.

Sleep Supplements

Sleep supplements helps you fall asleep easier. Here are some sleep supplements which you can try if you’re having trouble falling asleep:

  • Valerian
  • Melatonin
  • Magnesium
  • Theanine
  • 5-HTP
  • Antihistamines
  • Anti-depressants

You can look for these supplements on Amazon or Google. Just be sure to consult your doctor before taking any of these supplements. Because some might negatively affect an existing condition that you already have.

As a general rule, sleep supplements should be avoided and should only be taken when you really can’t sleep. They are just short-term fix, and they can leave chemicals in your body which can take around a week to fully expel. These chemicals might make you feel sleepy during the day which is not good for productivity.

Napping

You can nap around 20-30 minutes to gain a boost of productivity and avoid feeling tired or sleepy during the day. The best time to nap is around 1pm after lunch.

Sleep Tracking

If you want to have an idea how much sleep do you get per night. You can buy a sleep tracking device. Currently there are two brands which dominates this market: Jawbone and Fitbit. Just search for those on Amazon and pick one that feels right for you. These devices gives you a detailed look on how much sleep you get. That includes all stages of sleep that I’ve mentioned earlier. Its basically a wearable device (wristband) which you can then connect to an app in your smartphone.

Sleep Disorders

There are lots of sleep disorder out there but I’m only going to walk through these two: Insomnia and Sleep State Misperception.

Insomnia

Insomnia is a sleep disorder characterized by difficulty or inability to fall asleep. It can be either primary or secondary insomnia.

  • Primary insomnia – means that your insomnia isn’t caused by any existing medical condition.
  • Secondary insomnia – means that your insomnia is a result of an existing medical condition such as asthma.

If you believe you have an insomnia, its better to consult it to a doctor. A psychiatrist can help in most cases. Because oftentimes what’s causing you to not be able to sleep is only in the mind. If a psychiatrist cannot help you, then look for a sleep specialist.

Sleep State Misperception

Sleep State Misperception is the inability to perceive sleep from wakefulness. People with this condition may report having only slept for a few hours but in fact they have slept more than that.

Tips and tricks on falling asleep faster

Finally here are some tips and tricks on how to fall asleep faster:

  • Exercise in morning. Brisk walking, jogging or running will do. If you have a bicycle you can also use that.
  • Take a warm bath before going to bed.
  • Read a boring book.
  • Use a todo list, don’t try to hold things in your brain too much. As a developer, I always have things I want to do. Be it playing around a new technology, a library or a programming language. Or watching video tutorials and recorded talks from conferences all over the world. Or finally start a side-project I’ve been wanting to do for months. Or read an article about what’s new in the world of web development. Or write an article for my blog. The list is endless. The idea of a todo list is to put as much things outside of your brain as possible. This way you don’t have to think about it or maintain it on your brain like a file that’s saved in a filesystem in your computer.
  • Get into a journaling habit. A bullet list of all the things you’ve accomplished that day will make you feel at ease and awesome about yourself.
  • Picture yourself as dead tired.
  • Relax your mind. Imagine a beautiful and relaxing scenery such as the beach or mountain top. Basically anything that you find peaceful.
  • Use air-conditioning to lower the room temperature. A cool environment will make you fall asleep faster.
  • Turn off all the lights. If you can go pitch black or near pitch black do it.
  • Hypnotize yourself. Imagine a pendulum swinging in front of your eyes back and forth.
  • Listen to relaxing music. Look for soft piano pieces by mozart and put it into your phone or mp3 player.
  • Get out of bed if you really can’t sleep. If you still can’t sleep 30 minutes after going to bed then its best to get out and do something that would occupy your mind. Like watching TV or reading a book. Just go back to bed once you feel sleepy again.
  • Change position. Put your pillow to where your feet is currently pointing.
  • Take some deep breaths. Inhale then count up to four then expel it around 8 counts. Then repeat again until you feel relaxed.
  • Listen to a sleep hypnosis podcast.
  • Replay all the things you did in the morning in your head.
  • Stretch like a cat, curl your toes, or rub your belly. All of this somehow triggers us to yawn, which signals our bodies that hey its now time to fall asleep.
  • Don’t watch the clock when you can’t sleep. This will only make it worse as it makes you more anxious and pressured to fall asleep faster. Forcing yourself to sleep is no good. Just remember that it will to you eventually.

Resources

On Driving

| Comments

Its been a month since I started to learn how to drive. In this blog post I want to touch a bit on what I learned about driving so far.

Before Starting

  • Check the wheels if they are on good condition.
  • Make sure that both side mirrors are set.
  • Make sure that the hand brake isn’t currently active. In most cars all you have to do is hold the brake, press the button with your thumb and then push the lever down.
  • Just before you use the ignition key to turn on the engine, fully hold down the foot brake, set the car from park (P) to drive (D), then slowly release the foot brake.
  • Always remember to start slow. Apply as little pressure to the gas pedal as possible.

Overtaking

  • Don’t try to overtake if you’re not sure if there’s an approaching vehicle on the other lane.
  • Do not try to overtake on curves.
  • Do not try to overtake inside a town or a city.
  • Before trying to overtake a vehicle, check both side mirrors if there’s any other vehicle also trying to overtake.
  • Use the left signal light before trying to overtake to let others know that you’re trying to overtake. Once you’ve succeeded, use the right signal light and then go back to your lane.
  • When another vehicle tries to overtake yours, slow down a bit.

Emergencies

  • When an ambulance or police car is approaching or coming from your back, keep up with your normal speed and move the car to the side of the road to let them pass.

Curves

  • Slow down before approaching curves to avoid possible collision.

Intersections

  • Always slow down before approaching intersections. Around 20-30 kph. This is to make sure you don’t collide with other vehicles. You can never really know what approaches you in intersections so slow down.

U-turn

  • When going from one lane to the other make sure that u-turn is allowed.
  • If you want to give yourself more space, park your car on the side of the road first then when the road is clear, maneuver the wheel to the left. Most of the time you’ll have to turn the wheel to the left until its limit. If it isn’t enough, stop the car with the foot brake and then use reverse mode to move the car backwards a bit. Use the foot brake again and then turn the car to drive mode and turn the wheel to the left as much as its needed. Just before the car is completely facing in the right direction, turn the wheel to the right until its in its neutral position. Most wheels in modern cars actually go back to neutral position automatically but its safer if you don’t rely on that. Because most of the time you’ll want to move it to neutral position as fast as you can.

Speed

  • Don’t try to go faster than what you can handle. My personal limit is 60 kph, I don’t try to go faster than that.

Rough Road

  • If you actually care for your car, slow down when approaching rough roads.

Horn

  • Only use the horn when its absolutely necessary. Sometimes its prohibited to use it on some areas.
  • Do not use the horn to vent out your frustration. An example of this is when bicycle riders or sidewalk vendors use the road as if they were riding a car. Just give the horn a light tap, and if the bicycle rider still doesn’t move to the side simply go pass them if the situation allows.

Stay Cool

  • Be sure to keep your head cool at all times. You don’t want your driving to be affected because of your frustration.

Parking

  • Be sure that you are only parking your car where it is allowed.
  • Completely stop the car with the foot brake before putting the car into park mode and pulling the hand brake.
  • Be sure to leave enough space to maneuver your car later on. You don’t want to get to close to another car to avoid scratching it.
  • If the situation allows, use reverse mode when parking your car, this means that the tail of your car goes inside and the head is outside. This makes it easier for you to go out later on.

That’s it! I’m still a beginner at this so I’ll be adding more things to this blog post in future as I learn more things about driving. For now I’m going to leave you with this saying:

Better late than dead.

Introduction to Laravel Bootstrap Starter

| Comments

I’m still on side-project frenzy. This week its the Laravel Bootstrap Starter. I created this project to make it easier for me to setup a Laravel project faster. I’m using Laravel in the company that I work for and every time I start a new project I have to install it via composer, configure it so that it doesn’t show /public in the URL. From there I add the default controllers, add the sign up and login code, add the functionality for updating and resetting password, install node, grunt and then bower. And then install the grunt plugins that I need for front-end performance optimization. The list goes on, and just setting up a project may take a whole day. That’s why I decided to create this project.

Features

Like most of the projects that I decided to do so far. It only contains the essential features:

  • sign up and login
  • resetting passwords
  • admin (updating account information)

Future Plans

As I move along with this project I’m gonna be adding the following features:

  • social login – google, twitter, facebook, linkedin
  • database backup – every project must have an automated database backup functionality. I’m thinking of using cron for running the backup script and then upload the backup to an Amazon s3 bucket.
  • generators – there are 2 projects doing this already, one is Jeffrey Way’s Laravel 4 Generators and the other is Wes Dollar’s forked version, both looks pretty good. I think I’ll be able to get some ideas from these projects. Basically the plan here is to be able to use the terminal for generating boilerplate code which I can then build upon.
  • build tool integration – I want to be able to just hit one command and it will install and configure everything that I need to get the project started. Yeoman seems to be a very good fit for this.