Trying out Knockout JS

I have been reviewing Javascript frameworks for a few months now. Javascript Frameworks (aside from Mootools, jQuery, etc) have risen due to the need for Separation of Concerns, Testability, Abstraction and many others.

I never really focused learning any of these javascript frameworks. I have always liked to learn at least one but never had the chance to master one.

At my current company, there has been a rise of clients wanting to have their applications built using some sort of Javascript Frameworks with the likes of BackboneJS, Ember and AngularJS. For me, this was a wake up call to master something other than simple jQuery, Mootools or any low level DOM manipulation library.

I’m not good at comparisons nor am I going to elaborate on any reasons why I chose KnockoutJS. I simply liked how easy it was to develop simple scripts using it.

For now, I have been simply trying out samples and playing with them.

HTML Markup

<div class="offset2 span8 margin-bottom body">
  <h3>Concatenation!</h3>
  <p>First name: <input data-bind="value: firstName" /></p>
  <p>Last name: <input data-bind="value: lastName" /></p>
  <h4>Hello, <span data-bind="text: fullName"></span>!</h4>
  <h3>Calculation!</h3>
  <p>First value: <input data-bind="value: firstValue" /></p>
  <p>Second value: <input data-bind="value: secondValue" /></p>
  <h4>Hello, <span data-bind="text: calculatedValue"></span>!</h4>
</div>

Javscript Code

<script>
function ViewModel() {
    this.firstName = ko.observable("John");
    this.lastName = ko.observable("Smith");
    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);

    this.firstValue = ko.observable(1);
    this.secondValue = ko.observable(2);
    this.calculatedValue = ko.computed(function() {
        return parseInt(this.firstValue()) + parseInt(this.secondValue());
    }, this);
}

ko.applyBindings(new ViewModel());
</script>

As you can see, KnockoutJS is quite intuitive. It is easy to understand. This is just one reason I have taken a liking of this wonderful framework.

 Modules and Plugins Galore

If you're like me, you've been doing web development for 9+ years, you've been developing your `own site`, may it be a blog, a simple web portfolio, a gallery, by this time, you're probably getting tired.

I've written my blog site, gallery site and web portfolio more times than I could count. I have written CMSs just as much. A gallery project comes in, you write from scratch, another CMSs comes in your write another. How do I stop this circular madness?

The concept of modules and plugins didn't hit me until a few years ago when developing a gallery project using the Kohana PHP Framework. Jeremy Bush aka zombor developed a gallery as a module that could be put in to any Kohana project. It as interesting since I just dropped the module in my project, added a few styling, some configuration and voila! The gallery was up and running.

This concept just hit me again as I was working on my blog (yes, this one you're reading). I could write modules for almost every functionality. Any new feature, could be a module I could drop, configure and play with.

With that in mind, I have started rewriting it. Funny how the concept was to avoid rewriting and here I am rewriting software. But should I just continue writing it using CakePHP or should I try to write it in another PHP framework?

If you're someone who knows me, you'd guess that I've been writing the project and testing the idea using more than one framework. Yeah, that's right, two projects. In fact one is running a live site right now. One is on my local machine, waiting for the day I'd use it.

The PHP frameworks I have used are CakePHP using Plugins and Yii using Modules. This might be a topic I can write about more in a few days. But for now, wish me luck and focus, so that I may finish these projects. I might even opensource one of them when/if I feel comfortable.

See ya! 

 CakePHP's Has and Belongs to Many (HABTM)

Having worked with CakePHP on several projects, I have definitely found may quirks in how CakPHP works. There are instances that you would have expected things to work but doesn't.

One of CakePHP most wanted is CakePHP's Has and Belongs to Many (HABTM) relationships. Here is the easiest way to add HABTM relationship to a Model.


$type = $this->Type->find('first', array('conditions' => array('name' => 'Developer')));
$this->User->set(
    array(
        'id' => 1,
        'name' => 'Thorpe Obazee'
        'Type' => $type
    )
);


This without a doubt works! Our user will have a HABTM relationship with our Developer Type. Looking at this example, how would you add the User 2 HABTM relationships?

Well let's see.


$types = $this->Type->find('first', array('conditions' => array('name' => 'Developer'), 'limit' => 2));
$this->User->set(
    array(
        'id' => 1,
        'name' => 'Thorpe Obazee'
        'Type' => array($types)
    )
);


Would you have expected this to work? Well, it doesn't. Adding multiple HABTM relationships in CakePHP is quite different than adding a single one. Here's the way to add multiple HABTM relationships.


$types = $this->Type->find('first', array('conditions' => array('name' => 'Developer'), 'limit' => 2));
$type_ids = array();

foreach ($types as $type) {
    $type_ids[] = $type['Type']['id'];
}

$this->User->set(
    array(
        'id' => 1,
        'name' => 'Thorpe Obazee'
        'Type' => $type_ids
    )
);


Voila! This works! I have come to love CakePHP like any other framework I've used. I don't know if this is intentional on the part of the developers but I don't find it very intuitive.

 Logging in as another user in CakePHP

Sometimes, we are tasked with features like making an application administrator log in as a different user. This makes it an easy way for the administrator  to do task as  another user, see what another user is able to do and see. CakePHP makes it so easy for developers to implement this feature.

The steps are very simple:
  1. Store your admin details in another session variable
  2. Login user you want to be logged in as
Here is a sample code for implementing this:

    public function admin_login_user($id) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid User'));
        }

        $this->Session->write('Auth.Admin', $this->Session->read('Auth.User'));
        $this->Session->delete('Auth.User');
        $user = $this->User->findById($id);
        $this->Auth->login($user['User']);
        $this->redirect($this->Auth->redirectUrl());
        $this->autoRender = false;
    }
Logging out as the user is just as simple:
  1. Check if your session variable indeed has an admin session to log into after you logout as the user. Just a security check.
  2. Login as the Admin
  3. Delete the store where you saved the admin session

    public function logout_user() {
        if ($this->Session->read('Auth.Admin')) {
            $this->Auth->login($this->Session->read('Auth.Admin'));
            $this->Session->delete('Auth.Admin');
            $this->redirect($this->Auth->redirectUrl());
        }
        $this->autoRender = false;
    }
Frankly, I am loving how CakePHP does this.