Friday, June 12, 2015

Dojoapp with Codeigniter, Isuzu Malaysia

In continuation of my progress of developing and utilising Dojoapp, may I also introduce to you, Isuzu Malaysia. This project took us a good few months from inception to completion, and now live.

Some of the stuff I brought over from CakePHP is Layout, which is so uber important, but CI's team chose to not include even a simple library for layout. Here is my implementation of layout for Codeigniter. Which has worked so far for me in multiple projects since its inception.

Layout for CI

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Layout
    public $data = array();
    public $external_data = array();
    public $view = null;
    public $viewFolder = null;
    public $layoutsFodler = 'layouts';
    public $layout = 'default';
    public $page = 'pages/absolute/sample';
    var $obj;

    function __construct()
        $this->obj =& get_instance();
        $CI =& get_instance();
        $CI->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));

    function setLayout($layout)
        $this->layout = $layout;
    function setLayoutFolder($layoutFolder)
        $this->layoutsFodler = $layoutFolder;
    function setPage($page){
     $this->page = $page;
    function setData($data){
     $this->data = $data;
    function setExternalData($external_data){
     $this->data["external"] = $external_data;

    function render()
     $CI =& get_instance();
  $this->data["base_url"] = base_url();
        $this->data["site_url"] = site_url();
        $this->data["asset_url"] = base_url()."public_assets/";
        $this->data["resizer_url"] = base_url()."public_assets/resizer/image.php";
  $this->data["fb_app_id"] = $CI->config->item('fb_app_id');
        $controller = $this->obj->router->fetch_class();
        $method = $this->obj->router->fetch_method();
        $viewFolder = !($this->viewFolder) ? 'pages/'.$controller : $this->viewFolder . 'views';
        $view = !($this->view) ? $method : $this->view;
        $loadedData = array();
        $loadedData['view'] = $viewFolder.'/'.$view;
        $loadedData['data'] = $this->data;
         $loadedData['view'] = $this->page;

        $layoutPath = '/'.$this->layoutsFodler.'/'.$this->layout;
        $this->obj->load->view($layoutPath, $loadedData);

Notice I use loaded cache driver in the construction function, that's because I wanted the page to load faster the next time another user access the same page. This will reduce the load on my database server, which gets hit often for complex MySQL action! The above is just the library for layout, the view file for the layout however, is as below.

<!DOCTYPE html>
        <meta charset="utf-8" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height" />
  <?php $this->load->view("elements/meta",$data); ?>
  <?php $this->load->view("elements/ga",$data); ?>
  <?php $this->load->view("elements/basecss",$data); ?>
  <?php $this->load->view("elements/javascript",$data); ?>
  <title>Isuzu Malaysia</title>
  <?php $this->load->view("elements/nav",$data); ?>
  <div class="mh600">
   <?php $this->load->view($view,$data); ?>
                                //This is to temporarily disable the cache
                                $key = urlencode($_SERVER["REQUEST_URI"]);
     $cache = $this->load->view($view,$data, TRUE);
     $this->cache->save($key, $cache, 24*60*60);
  <?php $this->load->view("elements/footer",$data); ?>
  <?php $this->load->view("elements/crazyegg",$data); ?>

Passing data from Controller, via Layout to final view page

One of the hassles I encountered during development of this Layout library, is that I needed to pass data from Controller, to my view page, all the way through the Layout. And I needed a way to do that. My solution to that, is simply create another variable that can be set in the controller, then by exposing the variable to the view page through the Layout library, those data can arrive there safely!

Check out the "external data", that's where I pass the data in and use on the other side.

Wednesday, May 13, 2015

Browserify. Good News for NPM Wizards


Before I begin, let's answer a few crucial questions.

What's Browserify?
Hint: take a good visit for their website.
Hmm.. Ok, my bad. may be the tagline for browserify on their website isn't really helping at first glance, but bear with me. It blew my mind and changed how I tackle public dependencies, private packages and my general workflow right after I dived deep into using it in one of my recent projects.


I have an affair, with NodeJS

I have to admit, despite my love for Dojotoolkit. This is far more promising that it offers a few of the essentials that I found critical if you intend to bring your skill set up another level. But I will leave this part till the end of this article.

Let's now focus on what is Browserify?

My take on the explanation is this: It lets you code in very modular fashion and yet when you want to view it in browser, it can bundle/compile all of the dependencies that you are using into a single file. 


I was looking for similar workable solution for Dojotoolkit, unfortunately I don't think Dojotoolkit offers anything remotely close to this. Yes, it's modular, but it also means that the amount of files the browser needs to download also increases with the amount of modules I have. Which doesn't sound that bad, but if I can have a cleaner solution, fire it up I say.
Since Browserify depends very much on the community of NPMJS and the like to thrive, it will continue to get better as time goes by as developers are now realising that NodeJS is now recognised as enterprise class. As demonstrated by the guys from Walmart Lab. These guys are awesome, what they did at Walmart is that they created external modules using NodeJS to extend the legacy systems in Walmart with minimum impact. Walmart isn't your neighbourhood small time shop that only have few customers. And by using this new technology instead of relying on Java with IBM enterprise solutions or ASP.NET with Microsoft. These guys proved that for mission critical stuff, NodeJS is up to the task.

But, what does NodeJS and Browserify has in common?

Developers whom have started using Javascript may find it dreadful to go into another language such as PHP, ASP.NET, JSP you name it. But sometimes, and most of the time, developers need to cover from end to end and that means more language mastery is needed.

With NodeJS, developers can use their fluency in JavaScript to develop a backend that can act as some kind of CMS, or data retrieval from MySQL or MongoDB or even developing a realtime backend for interactive games! All this are made possible with NodeJS, it's using good ol JavaScript.

Browserify is like a nasi lemak bungkus

With Browserify, you can start all the way to architect your code with NodeJS's CommonJS modular style in mind and your code will still work in browsers! Isn't that neat? You will have the benefits of modular architecture that is easy to consume, easy to maintain and yes, easy to scale.

And let's not forget the awesome communities at NPMJS. The sheer amount of resources available for you to use is immense, a lot of the stuff that I always find trouble developing my own code for, I can always count that there is already a package that will solve my problem there.

NPM, Awesome Stuff

With NPM, you will be encouraged to best practices in dependencies management. You will create your own package.json that you can install all of your project's dependencies with single command of 

npm install

Nothing could be simpler than that, you just need to specify the version you needed for each dependencies that NPM will resolves all that and download automatically for you.

For example: package.son for one of my projects
  "name": "Chat.react!",
  "version": "0.0.1",
  "description": "Chat with React and browserify!",
  "main": "public/js/app.js",
  "dependencies": {
    "flux": "^2.0.0",
    "react": "^0.12.0",
    "underscore": "^1.7.0",
    "express": "4.10.2",
    "socket.io": "1.2.0",
  "devDependencies": {
    "browserify": "~6.2.0",
    "envify": "~3.0.0",
    "reactify": "^0.15",
    "watchify": "~2.1.0",
    "jest-cli": "~0.4.0"
  "scripts": {
    "start": "watchify -o public/js/bundle.js -v -d .",
    "build": "browserify . | uglifyjs -cm > public/js/bundle.min.js",
    "test": "jest"
  "author": "Shoguniphicus",
  "browserify": {
    "transform": [

You may want to learn a bit more about package.json, but take it at your own pace!

After the dependencies are downloaded into node_modules folders, you can go ahead and start the processing process that we can use watchify to automagically resolves and bundle up our codes into one nice JavaScript file

npm start

If you are wondering what's flux, react and socket.io and socket.io-client in the dependencies in my package.json. Feel free to check them out in their respective links. I should reserves this topic of using Browserify with Flux, ReactJS and also Socket.IO in my next articles. It's amazing how all these different parts play so well together to give us a whole new perspective on developing a webapp, or a website.

First Flux Project

Check this project out!

Tuesday, May 5, 2015

Dojoapp - Built from Dojotoolkit

For the past year or so, I have been working with Dojotoolkits for the most of my time, building several hybrid apps and website using it as a core. And also have been upgrading and cleaning up the little framework I called Dojoapp. (Not yet perfect, but it's already production ready!) Below is the short list of the projects that I have been able to complete last few months.

Yasmin - Howyouknow

This is my first web project using JavaScript with Dojotoolkit! The main challenge at that time was that I needed to animate those individual block of images in a direction with different top offset. At that time, the requirement was that, this page should also be playable in mobile devices! Madness!

What I did, was taking what I have learnt from AS3 (Flash, which was my bread and butter at that time), and apply it to accomplish what this site requires. The results, was simply amazing DIV-based animation that will work across major type of browsers, it even play nicely in IE6! Anyway, looking in hindsight, I realised that if I had known about HTML canvas, it would be far smoother and far better!. Still, the virgin JS project with Dojotoolkits.

Samsung Galaxy Wonderland

This, is the second project using Dojotoolkit, and even then, I hadn't any idea how to structure the front end of the site. I still remember at that time, I knew I needed a much more structured approach towards solving common web project problems. And I needed to form my own framework on top of Dojotoolkits (In case, you missed my previous article about why I chose Dojotoolkit and not AngularJS, Backbone and etc, go here.),

 photo ScreenShot2012-12-16at104739AM.png

Malaysia.my is my first attempt to make sense of how to actually crafting a good controller with factory patterns and also the concept of blocks and widgets. The 0.01v was born with this web project. It's also the first time I used i18n in a site that's finally bigger on the backend than just the bloated frontend.

U-Mobile Buahtangan

Talking about HTML Canvas in my first project, this is my first HTML Canvas web project that features a good hexagonal style fullscreen layout.

If you missed my previous article about my usage of HTML Canvas, go here.

KFC Golden Drumstick
If you missed my previous article about the challenge of developing this mobile web game, and the usage of PhaserJS, check it out here.


Shuttlefly, is the first hybrid app built on top of the Dojoapp framework that I have created while working on many of my web projects. It has a matured factory pattern, a matured controller, Objective-C inspired Navigation controller that can accept stack push of views and animate to give you the feel of native application and many more. Truly, this is the beginning of Dojoapp, mobile version.


Offpeak.my inherits most of its architecture from my previous projects. This project is where I created more utilities classes than all of my projects combined. A single selection modal, multiple selection view controller and many more. Go ahead and download them, you could enjoy very handsome discount at restaurants around Klang Valley!

Connected Mum's Club

*Some of the images here are taken from the google image. If you find it offensive, I will take it down. Wanted a screenshot of my web project as I don't usually keep my work
screenshotted". Too much to take care. :)

Saturday, December 20, 2014

Dojoapp - My First Opensource Project

The Introduction

This is a boilerplate where I wrote for a lot of my projects, ranging from mobile app to website for the past few years. The base is Dojotoolkits, which provides a good place to start. You may wonder, of so many other framework out there. Why Dojotoolkits? Why not AngularJS among others. My answer to that, is simple. Dojotoolkit has one of the easiest to setup in terms of its widget.

When you read on almost all of the recommendation out there that promote JavaScript framework, you will never hear Dojo or Dojotoolkit despite it being one of the best and easiest framework to learn so far. You will wonder, why are there no attention given to Dojotoolkits? May be, just may be that there is no good tutorial out there that makes people want to learn something as comprehensive as Dojotoolkits. And may be, dojoboilerplate will change your perception. At least, that's what I hope it would do.

Missing AS3 or Objective-C?

If you come from Flash Action Script 3.0 or Objective-C, you may have trouble setting up a good Javascript architecture that make sense in the long run. You may end up in spaghetti code where there is no real good practice in place, and everything just works. But what if, what I have developed so far, enables you to develop a full stack application on JavaScript? And you can finally have a more managable separation of logics from backend to frontend. Finally, a frontend framework that make sense.

I myself, have been exploring different frontend JavaScript framework. Most are okay to a point. But most fail at one feature where I think is most important. The ability to gel a Javascript "Class" to a template. Imagine if you will, every single piece of views that you see on a website is made up of a lot of template pieces. They may be the whole page, may be just the form area, the news section or even the breadcrumb.

Traditionally, what I would do, is to generate the whole page in backend platform of my choice, it can be PHP, ASP.NET, JSP and now NodeJS or others. Then use spaghetti code or jQuery to tie them to a function when the document is finished loaded and ready. Not a big problem, as developers have been doing this for the past decades or so without blowing up the internet.

Why the change?

It's more scalable, legible and best of all, easy to learn and use.

Currently, there are a few banking apps that are in the development process using the framework that I have managed to put together. And I am naming it dojoboilerplate. Beside this, there are already an app out there in the app store that uses this framework, it's called Shuttlefly.

Malaysia.my & Yasmin's How You Know

When I was in Leo Burnett Malaysia, I was tasked to develop Malaysia.my's frontend. The initial objective was simple, to get the site out quickly, as soon as possible, because the client's previous vendor has failed them miserably and the site is taking forever to update and to refresh. So, by the time the brief reached my table, it was almost reaching the deadline. So, we had to find ways to make this work. And at that time, I had just started playing around Dojotoolkit, and had only completed 2 projects prior to this incoming task. The first one was Yasmin Ahmad's How You Know website that was aimed to promote the book, if you don't know who is Yasmin Ahmad, may be you have seen her very touching and down to earth Petronas festive TVC, her passing away was a great lost to the industry as much as to the society. Personally, haven't have the chance to work with her, but from her legacy, I can feel she touched lots of souls and are well missed.

Samsung Galaxy Wonderland

The second website developed on Dojotoolkits was Samsung Galaxy Note campaign, it's called Galaxy Wonderland. I had to admit, because I had just started familiarising with how to structure a good Javascript fronted, the site was bloated and loading slow. Which we later found out how to speed things up and also cut down on stuff that's slowing the site down. And the experience of developing these two sites had benefited me greatly as it provide me the necessary challenge in a real world problem where I need to give solution to.


The framework will be released in Github, it will take me few weeks to find time to tighten up few more loose screws before I think it's ready for the 0.1v alpha primetime! Due to my current extreme amount of workload in my new position as Tech lead in Next Digital, one can only expect to see 0.1v in late January 2015. Hopefully, by then the framework will be even more mature and I hope it will help more people out there who struggles to choose a good Javascript framework.

If you must, and you will, please checkout Malaysia.my if you want to have a taste of what my framework would do.

As of current, my task is to deliver Connected Mum's Club within these coming few weeks. Same old story, previous vendor screwed up the site so bad that makes updating and upgrading the site's content difficult, if not impossible. Till then, happy coding!

Friday, October 3, 2014

[Bash Script] Semi-automatic Bash Minify Uglify Dojo Files!

As developer, you will want to spend most of your time developing than spending time minifying your script every time there is a change to the code and you will need to go through the process of minifying all of them. If you have like 5-10 javascript files, you may spend somewhere around 2-3 minutes minifying them depending on your choice of tools and how you want to minify and obfuscate your code.

2 - Minutes of manual minifying files

2-3 minutes is not a lot by itself, but when you add up those minutes when you have changes everyday, then you are bound to spend a lot more of your precious time on doing this tedious and boring work. And that's where bash script comes in handy, you are already using it in your terminal when you compile phonegap hybrid app, or when you install ruby or when you SSH into server.

I always thought bash script or anything you use in terminal makes you a hardcore programmer! That's my impression when I see people use terminal to access database server and application server to see where is the memory leaks and stuff, it makes me jawdrow, like literally, if reality allows.

I didn't know then, that using bash script allows me to do a lot of stuff that you normally would need a GUI that is programmed by other people to do something. And if what you need is from your own set of requirements, then you may need to write your own bash script to automate the tedious procedure that you want.

Dojotoolkit Evangelist

In my case, I am a Dojotoolkit evangelist. So, naturally, the amount of files for a typical complex web app will easily go up to hundreds of dependency files and widgets. And Dojotoolkit take AMD dependency injection to a whole new automagical level, which will allow your site to run lean and smooth while you can keep your source files organised and legible to a very good extent. Something that Angular.js has failed so far for me, hence my reluctance to move over to Angular. May be when they have figured out how to do widget properly, I will move over.

Almost Useless Dojo Build System

Dojotoolkits does have their build system, but there is a problem, there isn't even one good example of how to properly make a good build profile tutorial in the whole freaking site. It has good documentation, but those documentation is not good enough in my opinion. And require too much effort to learn something which should be painless and easy. Because the whole point is that you want people on board with you on Dojotoolkit, is that it's simpler and easier. I gave myself a good 1 months to tinker with how the build system works. I stopped after 1 week into the research because I find it too troublesome, and guest what, Dojotoolkit tutorial also feature someone else's custom boilerplate for building a profile because they themselves haven't figure how best to organise the file structures!

However, after using Dojotoolkits for all of my projects, including HTML canvas games. I have a verdict, it's good for everything. I even came up with a skeleton template that I can use for almost anything web and even hybrid app. The performance is there, the ease of use is there, the practicality is there, the reusability is there. Everything a web developer can dream of, and now I am tinkering into NodeJS. So might abandon PHP-based Codeigniter and give NodeJS a try in my future project that also runs on Dojo!

Ok, I mentioned my problem. Now comes the solution, I mentioned that I would have a lot of widget files and share elements classes across different folder structures that would require too much effort to minify them one by one and place them back one by one. So I went ahead and research about bash script and how it can automate this process, it took me around 15 minutes for me to search for the relevant syntaxes and command line before I can automate the whole freaking process!


To minify CSS, if you are already using SCSS or SASS, compass can already fulfil that requirement because you can choose to compact when it process your SCSS or SASS.

To minify JavaScript, you can use a series of tools found on the world wide web. It's everywhere! But specifically for the minifier that is Dojo-friendly, means it won't break Dojo style of code, it's recommended to use ShrinkSafe. There is a version where you download along side Dojotoolkit development set, it's inside the util folder.

To minify HTML, since Dojotoolkit's strength lies mostly in the power of widget, the amount of HTML file is also relatively huge because you make a template of whatever you need to reuse. Hence, it's also a good idea to minify those HTML widget file. And for that, I use htmlcompressor found in Google Code. The result is fantastic!

Now comes to the juicy part where we need to stitch up a bash code that automate the process of minifying, and obfuscating.

In order to do that, we need to consider a few things, - Retain the current folder structures as AMD loading style will always refer to the same folder path where the class is defined in Dojo - To switch from minify from source folder should be just a change of application path

So my first problem is solved by duplicating the current JavaScript folders into another folder and renamed it ending with _min. While I am at it, I will destroy all minified folders to make sure we don't get file override issue.


 rm -r $K_REL
 mkdir -p $K_REL

 cp -r $K_SRC/* $K_REL

Then we need to define those path that will be used over and over again in the entire script

 K_SHRINKSAFE="java -jar WHERE_YOU_SAVE_YOUR_FILE/shrinksafe.jar"
 K_HTMLCOMPRESSOR="java -jar WHERE_YOU_SAVE_YOUR_FILE/htmlcompressor-1.5.3.jar"

The Magical Part

 for file in `find "$K_SRC"`;

 currentfile=$K_SRC"/"`echo "$file" | cut -d/ -f9-`
 desinationfile=$K_REL"/"`echo "$file" | cut -d/ -f9-`

 if [[ $currentfile == *.js* ]]
 $K_SHRINKSAFE $currentfile > $desinationfile
 echo "JS - ".$desinationfile
 $K_HTMLCOMPRESSOR $currentfile > $desinationfile
 echo "HTML - ".$desinationfile

 #echo "$file | cut -d/ -f9-"


This is where the magic happens, where I find each files in the folder and minify them by either using Shrinksafe or HTMLcompressor depending whether they are JavaScript files or HTML files. HTMLCompressor is more error tolerant, so it won't stop the process from finishing when it tries to process, say a mac dust file or a PNG file or just an empty folder. Shrinksafe on the other hand, isn't that tolerant and will pause the process, which I find it rather restrictive. May be there can be a try and catch for batch shell script. But, so far, this has serve me very well. Hope it helps you too.

Thursday, August 7, 2014

[HTML JS] Hexagonal or Diamond Shape Masked Image

I am not entirely sure when did the creatives decide that hexagonal or diamond shaped images are the cool trend, because since last year I had been working on a project that requires user's avatar to be presented in such matter. At first, it presented a reasonable challenge because it's not possible to process all the images with Javascript to mask out the shape that we want, because that would be too taxing for any ordinary PC. Which would spells trouble especially client's PC tend to have weaker processing power and will very soon complain about the site being slow.

Hexagonal Image using HTML and CSS only

So, the other option that I could think of, would be to use canvas, but that too, didn't solve the problem of incrementally heavier load. And this dawn me, that I should utilize what new CSS has to offer and uses multiple overflow:hidden and css transform to rotate the image clockwise once and counter clockwise again. And the result is simply amazing, of course it takes some experimentation to get it correct.

Which, coincidentally, at the same time, I was working on a project that needed those techniques. But this time around, the mechanism is alot more complex and the hexagonal tiles are required to move around as desired. And this creates another problem that conventional html with CSS couldn't achieve with ease. Though that's not to say that we can achieve the same using just the layout with html and CSS, it's just a lot harder to predict the outcome.

I Chose Canvas

And so, I chose the easier way out, which is to use canvas based technology, which I had very recently been using in my game projects, the amount of learning and the amount of flexibility is amazing using PhaserJS. 

This project uses only PhaserJS as the main engine driving this website, even down to the hexagonal orange tiles that is laid out throughout the screen. The challenge here is to make the tiles arranged in such a way that they all tightly fit together and is able to change position with each other.

The bigger challenge is to have a center point where I could populate selectively avatars from, so there is no cheating here. It takes some thinking to put those code together.

The logic isn't rocket science once you know how to find the middle one, but to arrange the tile in a more meaningful way that you could arrange avatar from the middle point is a little bit more hair pulling. And the solutions that I had was gracefully short, around 4 lines of code to achieve that. I broke the problem into smaller problem and solve from there.

The Simple Algorithm

Firstly, we push all the hexagonal tiles into an array that we can use.
Then, we sort the array by comparing each one to the middle hexagonal tile
Finally, We can use. And here is the code snippet:

alltiles.sort(function(a, b) {  
return distance(yourself,a)-distance(yourself,b); 
function distance(p1, p2) {return Math.sqrt(Math.pow(p1.x-p2.x,2)+Math.pow(p1.y-p2.y,2));}

Now, isn't the solution simple?

As for the moving around part, it's easily achievable if you have work considerably with PhaserJS. The sprite class provides adequate support for animating things around with absolute ease. If you haven't start using any canvas game engine, you have to give PhaserJS a try. It's good.