Wern Ancheta

Adventures in Web Development.

How to Implement Infinite Scroll in Laravel

| Comments

In this quick tip I’ll be showing you how to easily implement infinite scroll in laravel. In the back-end, we will be using laravel’s pagination functionality. And in the front-end, we’ll be using jQuery infinite scroll. You can ahead and download the jquery.infinitescroll.min.js file from that page and save it on your project directory.

First thing that you need to do is return the data that you want to infinitely scroll from the controller:

1
2
3
4
5
6
7
8
9
10
<?php
public function getNewsPage(){
    $date = date('Y-m-d');
    $news = News::where('date', '=', $date)->paginate(10);
    $page_data = array(
        'news' => $news
    );
    return View::make('news', $page_data);
}
?>

And then from your view file (news.blade.php) just loop through the items that you wish to output:

1
2
3
4
5
6
7
8
9
10
<div id="news">
    <ul id="items">
    @foreach($news as $item)
        <li class="item">
            <a href="" target="_blank"></a>
        </li>
    @endforeach
    
    </ul>
</div>

Be sure to include jquery and jquery.infinitescroll.min.js file before the closing body tag:

1
2
3
<script src=""></script>
<script src=""></script>
</body>

Next, create the javascript file that will call the infinitescroll plugin and add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(function(){

    var loading_options = {
        finishedMsg: "<div class='end-msg'>Congratulations! You've reached the end of the internet</div>",
        msgText: "<div class='center'>Loading news items...</div>",
        img: "/assets/img/ajax-loader.gif"
    };

    $('#items').infinitescroll({
      loading : loading_options,
      navSelector : "#news .pagination",
      nextSelector : "#news .pagination li.active + li a",
      itemSelector : "#items li.item"
    });
})();

Breaking it down. First we wrap everything in a self-executing anonymous function to make sure that the script that were writing won’t have a way of messing up with the other scripts in our page, if any. Next, we setup options required by infinite scroll by means of a JavaScript object. Here’s a brief description of each:

  • finishedMsg – the html or text that you want to show once the user has reached the last page.
  • msgText – the text that you want to show while the next page is being loaded from the back-end.
  • img – the image that you want to show while the next page is being loaded from the back-end. Usually this is a gif animation that indicates that something is happening.

Next we call the infinitescroll plugin on the main news wrapper. This takes up an object as its argument. The object contains the following items:

  • loading – the loading options that we have setup earlier.
  • navSelector – the jquery selector that targets the pagination wrapper. Laravel gives it a class of pagination by default.
  • nextSelector – the element indicating the next page. Laravel adds the active class on the li representing the current page. So all we need to do is to traverse to the next one by using the + selector and then the anchor element.
  • itemSelector – an individual item.

Conclusion

That’s it for this quick tip. With the jquery infinite scroll plugin and laravel’s pagination functionality, you can implement infinite scroll in your apps with ease.

Getting Started With Twilio API

| Comments

In this article I’ll be walking you through the basics of using the Twilio API in PHP. But before that, what is Twilio? Twilio is a cloud communications company. They offer APIs which developers can use to enable Text Messaging, Voice, VoIP on their apps.

Now that we got the introduction out of the way. Let’s get started.

If you don’t have an account with Twilio yet now is the time to create one. You can do so from this page: Try Twilio. After signing up, Twilio will need to verify you’re a human. You can either have them call you or send you a text message containing your verification code. You’ll just have to select which country you’re in and then your phone number. Twilio already adds the country code as the prefix so you will only have to add your actual phone number. After you have verified your phone number, Twilio assigns you your first phone number.

twilio phone number

After that, Twilio will have you take your phone number for a spin. You can either make a call, send an SMS, receive a call, or receive an SMS.

twilio test drive

Go ahead and try atleast one of those options so you have an idea how it works.

SMS API

Twilio’s SMS API allows you to:

  • Send and receive SMS or MMS – when you signup with Twilio, you can purchase a phone number. You can then use this phone number to send text messages or multi-media messages to your users. At the same time, users can also send text messages to that phone number in order to interact with your application. How it works is that when a specific person sends a text message to the phone number that has been assigned to you by Twilio. Twilio makes an HTTP request to the URL you assigned to that phone number. The HTTP request contains the same data that the person sent. You can then use this data to have your app do what the user requested.

  • Track SMS Conversations – this allows you to track conversations between two phone numbers through the use of HTTP cookies. These HTTP cookies are use to keep a state. Just like when you login to a specific website. Cookies allows you to continue accessing the admin pages as long as you have that cookie around. After being active for some time, the cookie expires automatically. The same idea is used when tracking conversations with Twilio. Each phone number is assigned a cookie, and this cookie is sent along with the text message on every HTTP request made by Twilio.

SMS API Hello World

Now were ready to write some code. First create a composer.json file and add the following:

1
2
3
4
5
{
    "require": {
        "twilio/sdk": "dev-master"
    }
}

This tells composer to require the twilio sdk for PHP. If you don’t know what composer is. You can check out getcomposer.org to get started. Once you have saved the file, execute composer install from your terminal to install the twilio sdk.

Next, create a new PHP file then add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
require 'vendor/autoload.php'; //include the twilio sdk

$sid = "xxx"; //your twilio account sid number
$token = "yyy"; //your twilio account token

$your_twilio_phonenumber = ''; //the friendly name of your twilio phone number
$phone_number_to_send_to = ''; //the phone number to send the message
$text_to_send = 'Hello world! from twilio';

$client = new Services_Twilio($sid, $token);

//send message
$message = $client->account->messages->sendMessage(
  $your_twilio_phonenumber,
  $phone_number_to_send_to,
  $text_to_send
);

echo $message->sid; //the message id
?>

From the code above, the first line includes the twilio sdk. This allows us to easily make requests to the Twilio API. Next we declare the sid and token. You can find this on your account settings page under the API Credentials section. You can either use the live or the test credentials. The only thing to note is that when using the live credentials, your account is charged by Twilio. But if your account is in trial mode, you can only use the live credentials. Twilio doesn’t charge you when your account is in trial mode. But there are some restrictions. Going back to the code. Next we declare the twilio phone number. If you don’t know what your twilio phone number is, visit the numbers page. You’ll want to use the friendly name for your number. Next is the phone number where you want to send your message. This can be any phone number from any country supported twilio. Note that only United States and Canada are enabled by default. So you’ll have to enable sending a message to your country if you don’t live in any of those places. Just add a check mark to the country you want to send the message to. Next add the text that you want to send. Then create a new instance of the Services_Twilio class and supply the sid and token that we declared earlier. Finally, send the message using the sendMessage method. This takes up 3 arguments: your twilio phone number, the phone number to send to and the message. This method returns the following data:

  • sid – a uniqued id assigned to the message.
  • date_created – the date and time that the message was created.
  • date_updated – the most recent date and time that the message was updated
  • date_sent – normally this is empty when the request to send a message has just been made. Twilio messages doesn’t seem to be sent immediately when the sendMessage method is called (it is queued). Therefore its only natural for this to be empty and only updated when the message is actually sent.
  • to – the phone number where the message is sent.
  • from – the twilio phone number that you used for sending the message.
  • body – the actual text message.
  • status – the status of the message, normally this has a value of ‘queued’ right after getting the response from the sendMessage method. It is then updated to ‘sent’ once the message is actually sent. For inbound messages, the value for this is ‘received’. If the message is currently being sent, this will have a value of ‘sending’. If the sending failed, it will have ‘failed’ as the value.
  • num_segments – the number of segments the message has. Text messages are only limited to 160 characters so your message is divided into 160-character segments. Each segment are then sent separately.
  • num_media – the number of media items associated with your message.
  • direction – can have a value of outbound-api, inbound, outbound-call, and outbound-reply. These are basically like the name suggests, outbound-api are the messages you have sent from your app. inbound are the ones that are sent from an actual phone number to your twilio phone number. outbound-call are the messages initiated during a call. And outbound-reply are messages initiated in response to an incoming SMS.
  • api_version – the twilio api version used when the message was sent.
  • price – the amount billed for the message.
  • price_unit – the currency used for the price.
  • error_code – the error code returned. This will only have a value if the value for status is failed. If you are having an error returned to you, be sure to check out the errors reference.
  • uri – the uri of the resource used for sending the message.
  • subresource_uris – the sub-resources used in sending the message. For SMS, a possible sub-resource can be the media resource.

Dev Tools

Before we move on to writing some more code. I’d like to do a quick introduction on the dev tools offered by Twilio. Twilio’s dev tools includes the following:

  • App Monitor – allows you to monitor the requests being made to your app. These requests can be an outbound test/call to a specific phone number, or an inbound text/call to your twilio phone number. Basically, every interaction to your app are logged in the app monitor.

  • API Explorer – allows you to make and explore API requests. This includes the parameters needed for a specific resource and the response that it returns. The good part is that it also includes code samples in different programming languages. Which you can readily copy and paste in order to test in your application. One thing to note when making requests through the API explorer is that you get charged for specific resources. An example of such resource is the resource for sending messages.

  • Connect Apps – allows you to create a twilio app for the purpose of letting your clients connect to it. This allows you to perform specific actions on behalf of your client. If you’ve ever used the Facebook API before, its pretty much the same idea. The only difference is that its your clients twilio account that is connected to your app. This is useful for clients who have their own clients. This allows you to send messages or make calls to the clients of your client on their behalf. This means all the charges are being made to your clients twilio account instead of yours if you choose to.

Searching and Buying Phone Numbers

If your app allows your users to have their own phone numbers. You can also use the twilio API to search for available phone numbers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php

$area_code = 201; //only for US and Canada
$search_params = array(
    'AreaCode' => $area_code
);

//make a request to search for available phone numbers on a specific area
$numbers = $client->account->available_phone_numbers->getList('US', 'Local', $search_params);

$nums = array();
foreach($numbers->available_phone_numbers as $n){
    $nums[] = json_decode(json_encode($n->phone_number), true);
}
?>
<pre>
<?php print_r($nums); ?>
</pre>

You can supply the following arguments for your search:

  • AreaCode – any valid area code in US or Canada.
  • Contains – a regular expression for matching the characters you want the phone numbers to have.
  • SmsEnabled – if sms capabilities are enabled. This can either be true or false.
  • MmsEnabled – if mms capabilities are enabled. This can either be true or false.
  • VoiceEnabled – if making and receiving calls is enabled. This can either be true or false.
  • ExcludeAllAddressRequired – if you want to exclude the phone numbers that require an address or not.
  • ExcludeLocalAddressRequired – if you want to exclude the phone numbers that require a local address or not.
  • ExcludeForeignAddressRequired – if you want to exclude the phone numbers that require a foreign address or not.

Once your user has selected a number, you can then make a request to buy a phone number:

1
2
3
4
5
6
7
8
<?php
$phone_number = $_POST['phone_number'];

$number = $client->account->incoming_phone_numbers->create(array(
            'VoiceUrl' => 'http://yourwebsite.com/greet',
            'PhoneNumber' => $phone_number
));
?>

The request requires two arguments: the VoiceUrl, which is the URL which you want Twilio to make a request to when this specific phone number is called by someone. We’ll talk more about this on the TwiML section, which is Twilio’s way for interacting with users in a call through a computer voice. The second argument is the PhoneNumber, which is the phone number selected by the user which came from the search results earlier. Note that making a request to purchase a phone number costs money.

TwiML

TwiML or the Twilio Markup Language isn’t exactly a new markup language created by Twilio. Its basically just plain old XML which you can use to do all kinds of cool stuff when a user calls your twilio phone number. Here are a few examples of awesome stuff you can do with TwiML. Note that these are all performed during a call:

  • Play – allows you to play an audio file.
  • Say – allows you to convert text to speech.
  • Dial – dials another phone number that can then be added to the current call.
  • Record – record the voice of the caller.
  • Sms – send a text message.
  • Gather – allows you to gather the users input. Currently inputs are only limited to numbers.

Now that you have an idea what you can do with TwiML, lets move on to some practical stuff. Let’s build an app that allows the user to input a number and have a different sound played based on the number.

Start by creating a hello.xml file, then add the following:

1
2
3
4
5
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Say>Hello! Please enter a number from 1 to 5</Say>
  <Gather numDigits="1" action="/choose.php" method="POST" />
</Response>

What this does is allows you to control the response that the user hears when they call your twilio phone number. The first line specifies the xml version and the encoding. The second line is the response wrapper. This allows us to specify the actual response that the user will hear. The first thing that the user will hear is the speech version of the text that we added inside the Say verb. In this case, were asking the user for a single digit number from 1 to 5. Next we use the Gather verb to gather the digit entered by the user. The numDigits attribute allows you to specify the number of digits. This has an added benefit of submitting the response immediately after the number of digits you specified matches the number of digits entered by the user. The digits entered by the user are submitted to the page you specify on the action attribute. In this case its the choose.php file in the same request URL you added to your twilio number. If you don’t know how to change the request URL used by your number, then visit the numbers page and click the number you want to use. That will redirect you to the settings page of that number. From there look for the voice section and then change the request url then click save. This means that if your request url is ‘http://mywebsite.com’ and you specified ‘/choose.php’ as the action, then you need to have the ‘choose.php’ file in the root web directory of your website in order for the digits to be submitted properly.

Add the following code to the choose.php file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
header("content-type: text/xml"); //specify content type to be xml

$digits = $_POST['Digits']; //the digit inputted by the user in his/her phone

//the array of sounds that we will be playing back to the user
$animals = array(
    'bassethound.wav',
    'cat.wav',
    'cattle.wav',
    'chicken.wav',
    'sheep.wav'
);
?>
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Say>Here is the sound you selected</Say>
  <Play>http://mywebsite.com/sounds/<?php echo $animals[$digits - 1]; ?></Play>
</Response>
?>

From the code above, the first line specifies the content type to be xml. The second line is where we get the digits enterred by the user. Next we declare an array containing the sounds that we want to play. I got these sounds from animal-sounds.org. Next we just set the response starting with a speech saying ‘Here is the sound you selected’, then we just play it back using the Play verb.

Conclusion

Twilio’s API allows you to add SMS and Voice superpowers to your apps at ease. Their documentation, quick start guides can get you up and running pretty quickly. Their code samples include some of the most popular programming languages for the web. Such as PHP, Ruby, Python, Java and .Net. If you need to add SMS and Voice capabilities to your app, there is no doubt that Twilio should be your first choice.

Resources

Introduction to Antares

| Comments

As a developer there’s no question as to why we need to keep ourselves updated. And that is why reading blogs is really important. There’s no shortage of the most important people to follow on twitter, newsletters, podcasts and screencasts that helps us to keep up to date. But as the years pass the amount of resources that we use to keep ourselves updated tends to grow. This results in a browser window that looks like this:

too many tabs

Just the act of opening the interesting links in new tabs can take up to 30 minutes or more (I know, I’ve been there). All because of the sheer amount of resources that were trying to maintain. I’ve been doing that for years, and as my collection of resources grew larger, it only became harder and harder to read all of those things that are seemingly important. That is when I had the idea of creating an app which would still allow me to keep up to date, but will save me the time in opening all those links in a new tab. That is what Antares is all about. Its essentially a news app for developers. It collects content from interesting places such as Hacker News, Github, Designer News, Medium, Readability Top Reads, Slashdot, EchoJS, SidebarIO, and Product Hunt. It also collects all the content linked from popular developer newsletters such as JavaScriptWeekly, HTML5Weekly, PHPWeekly, CSSWeekly, Web Design Weekly and many others. Its basically an all in one tool for keeping up to date. As for me, it also have the effect of just letting go. Because having all those newsletters sent in my email has this mental effect that its something I need to open no matter what. The kind of feeling that its your responsibility to read through all those articles being pointed out in the newsletter. The feeling that you’d miss out on something really important if you don’t. Antares isn’t like that. You can just install it and let it sit there. And you only really open it if you have some free time. The news just keeps on flowing in there but it doesn’t make you feel that you’ll miss out on one half of your life as a developer if you don’t.

For the technical side of things, I used Ionic framework to build the app. Under the hood it uses HTML, CSS and JavaScript. Ionic is tied with Angular.js so there’s really not much choice about what JavaScript framework to use. For the back-end I used Laravel to scrape the necessary data from all the relevant resources. It is then stored in a MySQL database. The data (mainly a title and a URL) is then requested via AJAX from the mobile app. Ionic then handles the presentation. To give you an idea, here’s a couple of screenshot of how the app looks like:

hacker news

article

As a developer who loves working on the back-end, I didn’t really bother customizing the look and feel of the app.

This blog post is getting rather long for an introduction. Here’s the link to the app on Google Play Store. If you got a Windows Phone, I also have the .xap file which you can use to install Antares. Antares doesn’t have a version for apple devices. Mainly because it costs around $99 per year to be included in their developer program. As someone who doesn’t really plan to make any money out of this. I think its unwise to pay for that amount. I’m already paying $10 per month for the server costs and I paid $25 to put the app in the Google Play Store so I guess that’s enough expenses on my part.

ToDo List Driven Development

| Comments

In my daily work as a developer I always have this file which I call todo.txt. It contains all the things that I plan to work on, currently working on, and those that I’ve already done in the past. They are ordered from the most recent day that I’ve worked on the project to the least recent. These todos are stored in their own folders, named after the name of the project. Here’s the general format that I follow:

1
2
3
4
5
6
7
8
9
10
FEB 7, 2015

TODO
- list of things that I'll be doing

DONE
- list of things that I've done
=========================

FEB 6, 2015

This is the first file that I open when I start working. It gives me a quick overview on which things I’ve already finished and which things are left undone.

The items in the todo list often represents individual features that I have to work on. If the feature is too big (may take around 2-5 days to implement), I break it down into tiny bits to reduce the mental strain. Because holding one big feature in your short term memory is hard. I want to make my todo list as stupid as possible. So I can focus on writing the code and not needing to hold many details in my head. It would often look like a step by step procedure (algorithm) of sorts. Here’s an example from the booking app that I’m currently working on:

1
2
3
4
5
6
7
8
TODO
- add code for scheduling new appointments
 - use the combination of page url and service url as basis for selecting the needed data from the database.
 - once all the necessary data is in place, use it to get the time settings from the database.
 - use the time settings to generate an array that stores all the available times.
 - get all the times which has already been used in an appointment
 - get the settings on the maximum appointments that can be scheduled per day, the minimum scheduling notice, and the maximum number of days into the future can appointment be scheduled (to prevent scheduling something on year 2099 while its still 2015).
 - loop through all the available times. While inside the loop exclude all the times which has already been used in an appointment, also exclude the times based on the settings above.

Of course it doesn’t end there, but you get the idea. Make every item or in this case sub-item as stupid to implement as possible. If you think it would help to break each sub-item down some more, then do it.

Aside from the features I need to implement, my todo.txt file is where I also put details on the current project that I’m working on. As I’m primarily using Amazon ec2 instances on my projects, the details that I put on top of the file are the ip address, the domain name assigned to the instance and then the user and password for the database. Yes it would be more secure if I put them on a password manager such as keypass or lastpass but I prefer fast access over it. I just want everything that I need for the job to be in one place.

Lastly, when I’m doing research for the project that I’m currently working on. I also put in some relevant URLs which I could easily go back to later on once I implement a specific feature. When I find myself going back to access a specific page very often, I just copy the specific content that I need and paste it on the file. Here’s a sample snippet, these are the set of commands that I use when building a phonegap app:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#build phonegap app
cordova build --release android

#generate app key
keytool -genkey -v -keystore stockswitch.keystore -alias switch -keyalg RSA -keysize 2048 -validity 10000

#sign the app with the key
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore stockswitch.keystore CordovaApp-release-unsigned.apk switch

#build a release version
zipalign -v 4 CordovaApp-release-unsigned.apk stockswitch.apk

#output the certificate
keytool -exportcert -alias switch -keystore stockswitch.keystore | openssl sha1 -binary | openssl base64

That’s it! Having a todo.txt file at my disposal is really helpful in my day to day life as a developer. It helps keep the mental load to the minimum by having all the details that I need all in one place.

How to Market Yourself as a Developer

| Comments

As a developer who mainly do remote work, its important for me to get my name out there. Because that’s the only way people would know if I’m actually any good or I’m just faking it. That’s the only way for potential clients to know if I actually have the skills required for the job or the project they wanted to build. In this post I’ll be looking into some of the things a developer can do in order to market themselves. I already apply some of these tips as a developer. And some are the ones that I wish to do in the future.

Blogging

Start a blog where you document all the things that you’re learning with regards to your craft as a developer. If you’re a web developer go ahead and publish articles on PHP, Python, Ruby or Java. Front-end guy? Then blog about HTML, CSS or JavaScript. Angular, Backbone, or Ember if you’re using that. Do you do some hybrid app development? Then do an article on Ionic or Titanium. Developing with Wordpress? Then write something about that cool Wordpress theme or plugin you have released recently. Worked with some cool API on your day job? Then tell the world about it. You get the idea. Whatever your niche is, try to come up with a specific topic and then write about it. You don’t have to be 100% accurate about everything you write. It doesn’t have to be 100% correct all the time. Its your personal blog after all.

Okay so why a blog? Because that’s the easiest way you can prove to someone that you have worked with a specific technology in the past. And that you’re good enough to be able to write an article about it. Remember that popular quote that goes something like:

If you can’t explain it to a six year old, you don’t really know it yourself.

That’s what blogging does. You know that you have understood a topic when you write about it. And it makes sense when someone other than yourself reads it.

If you are more of a talker than a writer. Or you don’t really like the idea of staring at your computer for hours constructing a blog post then you can do alternatives such as podcasting or screencasting. When I was new to programming this guy named Bucky Roberts was the authority. He’s like the programming god or something. His youtube channel thenewboston is full of screencasts related to programming. Android, IOS, Python, PHP, HTML5, C++, C#, Objective C. You name it he’s got it. And there’s this other guy (I don’t know what his name is) who is basically the authority when it comes to PHP mainly because of the amount of PHP screencasts that he has put out there in his youtube channel phpacademy.

If you want to start screencasting, all you need is a recording software, decent microphones (if it doesn’t sound terrible when you play back your recording then its decent), and a webcam (optional if you don’t want people to see your face). For Windows there’s CamStudio. For Ubuntu, there’s RecordMyDesktop. And for Mac there’s Screen Capture.

So how is all this gonna get me clients? Simple. It allows you to put yourself out there. And when you’re out there in the internet with all your free awesome content. People are bound to find you at some point when they google a specific problem they are having or they’re just browsing around looking for something.

After some time (maybe a year or two), you can now try writing for some of the most popular blogs or websites in your field. If you’re a web developer, you can write for Sitepoint, Tutsplus, or Smashing Magazine. There are some others which are also popular but those are the only one’s I can name on top of my head. The clear benefit is being able to reach a wider audience. Sitepoint and Tutsplus also pay their authors once an article is published. I’m an author in the Sitepoint’s PHP Channel myself so I can vouch for that.

Social Media

An important part of having an online presence is social media. Have a new post on your blog? Tweet it. Liked a blog post by a fellow developer? Like it or +1 it. Heck comment on it too. Just make sure its a useful comment. You can also post links to the articles that you’ve read regarding development. You can use buffer or ahead (shameless plug) for that.

Side Projects

As developers normally we would work for a company or a client. So we don’t really get to show people the code that we write on a day to day basis. And that is why its important to have side projects and put them in Github or Bitbucket. That’s the only way for potential clients or bosses to have a clear picture of your coding skills. Just like with blogging, podcasting or screencasting your code doesn’t have to sparkle like a diamond. It doesn’t have to be perfect. If you are early on in your career as a developer, all those best practices like applying design patterns in your code, SOLID, YAGNI or DRY or whatever acronym wouldn’t be there. It doesn’t matter if you have applied TDD or BDD in your project. It doesn’t matter if you didn’t use LESS, SASS, Stylus, Bower, Grunt or Gulp. It doesn’t matter if you didn’t use browserify or requireJS. We all get to use some of those at some point in our career. What’s important is you put your code out there. Who knows it might help someone and then they give you money through flattr or paypal. You can also point out your Github or Bitbucket profile when applying for jobs or showing off what you can do.

Networking

Last but not the least is networking. Its the one thing that I ought to be doing but never really done. But now I’m trying my best to do some networking by joining the freelance team at slack, its a place where fellow freelancers can have a nice chat online and maybe schedule meetings offline. I also try to accept most of the invites on my linkedin account. And then try to be helpful by providing testimonials for the people that I personally know. Twitter is good for this as well. For example, you read an article which you found helpful. You can say thanks to the person who wrote the article through your Twitter account. Follow the person. And hopefully they will respond and that can start a conversation. Lastly, always try to be helpful. If someone comments on your blog, try to respond. If someone adds you on Skype asking questions about that article that you’ve written or that side-project you released on Github, accept them as a contact then respond to them. Who knows they might be the one bringing you a cool awesome project in the future.

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.
  • Shopify Series – I want to learn more about Shopify since I’ve been getting lots of Shopify projects lately. Because of this article that I’ve written 2 years ago about getting started with shopify app development. I had to decline all of those projects since I’m not confident enough on my Shopify Development skills. And so I think that doing more Shopify is the only solution. And I’ll document everything that I learn on this blog in a form of a series of articles discussing about various Shopify topics.
  • Prediction IO Series – just like Shopify, I’m also getting a lot of projects concerning Prediction IO. So I also want to dive deeper so that I can feel confident enough about taking projects.

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.