Random thoughts | Hari KT

On programming

AngularJS by Brad Green, Shyam Seshadri; O’Reilly Media

First I would like to apologize O’Reilly for the dealy it happened. So the buzz is AngularJS.

I took the book AngularJS by Brad Green, Shyam Seshadri; O’Reilly Media for review. Both authors Brad Green and Shyam Seshadri has experience working at google and angularjs.

I have noticed people rating 5/5 mentioning the book covers to the point etc. I am really new to angularjs and my reviews are based on it.

I don’t think I can recommend the book for a person who is really new to angularjs. Though it starts simple, at some point of time it jumps to advanced parts or hard to follow. Don’t think it is the problem with book itself but the concepts are new and need a better way to explain. Eg directives.

I strongly feel the introduction of yeoman, karma etc has added more frustration. But I do like the introduction of debugging tools like Batarang.

These could have been taken to the last chapters if really needed. There are many places where it could have been explained with better examples than just small snippets of code where people don’t know where to keep and figure out themselves. Though there is a github repo with code, chapter-5 doesn’t have one.

I can give a rating of 3/5.

Rentautobus Back to India

Rentautobus.com is a worldwide private transport quote comparison and reservations portal which was my first live project that made my hands dirty with Zend Framework. I was hired as a maintainer for the multilingual website.

Multilingual websites when viewed from outside is not that complex. Before you dive into write your first line of code, everyone should read The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

Many of the developers don’t care about the characterset and finally they see weird characters displayed and your client re-opening the same tickets. I don’t blame any developers for until when you deal with something like this you will end up in trouble.

Tests!

How many of you really test your app?

Most of them, or the QA does it for you. Awesome!

But I am not talking about manual testing. Hope you have heard about automated testing tools like phpunit. How many of you write unit tests? How does that help you?

Say you have the equation (a+b)2 = a2 + 2ab + b2

What you do is write a simple class with the method which returns the result.

Everyone knows the expected result. But in most cases it may not be the same. May be there is a new feature coming, if a is less than b use

(a-b)2 = a2 – 2ab + b2

Now the complexity is increasing. And at somepoint of time you could not test each one manually and unexpected results coming.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
class Algebra
{
    public function calculate($a, $b)
    {
        if ($a < $b) {
            $result = $a*$a + $b*$b - 2* $a*$b;
        } else {
            $result = $a*$a + $b*$b + 2* $a*$b;
        }
        return $result;
    }
}

In-order to get rid of the already tested one, writing unit tests is the nice way. So the test will be something like

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
<?php
class AlgebraTest extends PHPUnit_Framework_TestCase
{
    protected $algebra;

    public function setup()
    {
        $this->algebra = new Algebra();
    }

    /**
     * @dataProvider provider
     */
    public function testCalculate($a, $b, $result)
    {
        $this->assertEquals($result, $this->algebra->calculate($a, $b));
    }

    public function provider()
    {
        return array(
            array(3, 2, 25),
            array(2, 3, 25),
        );
    }
}

Here if you noticed what will happen when a and b are same?

What I am trying to point out is write tests, so the person who comes as a maintainer also can run the tests and see everything is working as expected.

Probably your client may blame you for taking more time, try to convience them that it has saved X Hours to fix the bug!.

Be brave and start writing tests, for the next maintainer don’t have to find whether it was a feature request or this is a bug.

No one can learn everything in a single day, start small to achieve big.

What rentautobus.com does?

The idea of rentautobus.com is to help both groups of people and individuals who are travelling to a different place/country to easily get quotes from private transport operators or travel agents. They can compare offers and quality, go through the reviews and feedback comments of people who have already travelled with these transport providers, how comfortable are they with the vehicle, the driver etc. The feedback system is not a new one, it’s called 5 star rating which is mostly used by travel and hotel websites.

In the promotional video below you can see the concept explained. This comparison concept is quite comon in Europe.

You can choose from a wide variety of travel agents, easily compare the price what they offer, the feedback they got from others. The 1st concept of the website was built for European countries like Spain. And
as of today the site has expanded to other countries like India.

Rentautobus recently added Car with Driver services in Cochin to the list of countries, places and services offered.

Will the concept in India work like Spain?

I’m curious to see if this European concept will have the same acceptance in India as in Spain.

Cultural differences do exist and this of-course translates into the use of internet as a research and booking tool for transport, tours or other travels. Travel arrangements in India by people over here are often done via a trusted travel agents who normally is a friend or introduced by a friend or family member.

For foreign tourists traveling to India for the 1st time, with no local contacts its of-course a good thing to have a friendly internet reservation tool for their transport arrangements.

We are not sure yet how the system should be adapted to fit the local Indian cultural requierments.

Let us know your thought and opinions!

Give Away: Getting Started With Laravel 4

With the help of Packt Publishing, there is a small contest started for Giveaway of the book, Getting Started with Laravel 4.

And three lucky winners stand a chance to win a digital copy of the book on Laravel 4. Keep reading to find out how you can be one of the Lucky Winners.

Overview:

Provides a concise introduction to all the concepts needed to get started with Laravel

Walks through the different steps involved in creating a complete Laravel application

Gives an overview of Laravel’s advanced features that can be used when applications grow in complexity.

Learn how to build structured, more maintainable, and more secure applications with less code by using Laravel

How to Enter?

All you need to do is head on over to the Book Page,
look through the product description of the book and drop a line via the comments below this post to let us know what interests you the most about this book. Then tweet the same using the book link: http://bit.ly/KwzF9j. It’s that simple.

Winners will get an e­copy of the Book.

Deadline

The contest will close on 9th Feb 2014. Winners will be contacted by email, so be sure to use your real email address when you comment!

Happy PhPing!

Frameworks Are Good, Components Are Awesome!

Some of the recent discussions in the PHP world are

Framework is not a bad idea

If you don’t use a framework, probably you will be using a bunch of independent libraries glued together or some code which help you to achieve your task.

Whether we use a framework or independent library, our ultimate aim is building the right product for our customer.

If you are building an app, and if you strongly feel symfony is the right choice you should go with it. And if you feel zend framework, auraphp, fuelphp, cake .. (you name it) is the right one you should go for it.

The ultimate aim of any framework developers is to make a living from it or to advertise his capability. So all will advertise it as good and never say a bad word even if they know the pit falls.

One of the recent problem we can notice is every php framework tries to advertise they are developed from components.

First

Laravel is an awesome framework, so do symfony, zend framework and you name it.

and not to your surprise “I love auraphp

Don’t call all are build from libraries

May be we need to define how/why we call it as library.

Consider a routing library : You give a URL path and $_SERVER values it extracts the route information.

Some of the libraries that does the work are aura/router, symfony/routing, illuminate/routing

Apart from aura, I did a search for routing in packagist

If you have a good eye, you would have understood looking at the packagist dependencies.

The next one is regarding the require-dev. The require-dev dependency is when you want to bind other components. The best way is to get rid of the require-dev. The glue package should be another independent package.

Consider Lusitanian/PHPoAuthLib Symfony session has one. What will happen when someone who loves zend, aura, fuel etc love to have the session. It gets overly complicated. So is https://github.com/friendsofaura/OAuthSession repo born. Another good example I would like to show is aura/project-kernel

Yes it is a bit of hack, to run tests. Have a look into travis

What I love to see in the PHP world is have a single repo where the pull request, create issues can be made rather than going and forking the entire code base. And not to mix the source and tests.

The packagist need a way to sort dependent packages, independent packages and framework dependent packages.

If you are new to PHP, I will recommend you to use components and glue it together.

Your application defnitely at some point of time need Input Filtering & Validation

May want to introduce form libraries to glue with your legacy code.

You will learn PHP, and not the magic of a framework. Depending upon the dependencies it will be easy to replace the component. That is the ultimate aim of components, not to trap you.

Thanks for reading.

Happy PhPing!

Composer Support for ProcessWire : Part-2

In my earlier post I mentioned about adding a composer.json in the root of the github repo.

Sometimes you may see a non composer.json repo or some times people reject it, you still can do like the below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
    "minimum-stability": "dev",
    "repositories": [
        {
            "type": "package",
            "package": {
                "name": "ryancramerdesign/process-export-profile",
                "version": "1.0.0",
                "source": {
                    "url": "https://github.com/ryancramerdesign/ProcessExportProfile",
                    "type": "git",
                    "reference": "master"
                },
                "type": "pw-module",
                "require": {
                    "hari/pw-module": "dev-master"
                }
            }
        }
    ],
    "require": {
        "ryancramerdesign/process-export-profile": "1.0.0"
    }
}

And run

1
php composer.phar update

Don’t forget you need composer.phar. If you don’t have get from getcomposer.org

The module is downloaded to site/modules/ProcessExportProfile. The package is of type pw-module

The name process-export-profile is converted to ProcessExportProfile . So if you have caps in between name put a hyphen in the naming

Composer Support for ProcessWire Modules

I am a huge fan of composer. PW ( ProcessWire) is missing one of the good parts of composer. So here is a new installer to install the 3rd party modules of PW via composer.

If you have created a module for PW, what you need to do is add a composer.json file in your github repo and add it to packagist. An example composer.json is

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
    "name": "vendor/package-name",
    "type": "pw-module",
    "description": "Your module what it does",
    "keywords": [ "keywords", "comma", "seprated"],
    "homepage": "https://github.com/harikt/Assets",
    "license": "BSD-2-Clause",
    "authors": [
        {
            "name": "Assets Contributors",
            "homepage": "https://github.com/harikt/Assets/contributors"
        }
    ],
    "require": {
        "php": ">=5.3.0",
        "hari/pw-module": "dev-master"
    }
}

Note the minimum requirement is PHP 5.3 for composer is 5.3 .

An example of a module that works with this is https://github.com/harikt/Assets ( Move the index.php to any where :–) ). You are read more about Assets from here

Installing modules

How do you install the PW modules and the 3rd party dependencies ? Assuming you are in the PW folder.

First download composer from http://getcomposer.org/download/.

Hope you have composer.phar now.

1
php composer.phar require vendor/package-name version-name

Will install if the vendor/package-name to site/modules/PackageName. All packages vendor/package-name of "type": "pw-module" will be converted to PackageName.

Example you can try

1
php composer.phar require hari/assets dev-master

Try the above and see where it is installed. If you are a module maintainer, please add a composer.json to your github module and add it to packagist.

Of-course inspired and modified composer installer from Aura Project for PHP

Thank you. Happy PhPing!

Assets for Processwire

Processwire is a content management framework.

I was looking to change the directory structure of the Processwire.

1
2
3
4
5
|-- index.php
|-- installer.php
|-- README.md
|-- site
`-- wire

I am not the first person to talk on the subject. There are other threads like Installation paths and moving folders, Common practices

Anyway I thought of trying the same and for serving the js, css, images I wrote my first processwire module Assets

Some of the portions are from Aura.Framework and Aura.View

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|-- cli
|-- composer.json
|-- index.php ( which is moved to web folder )
|-- installer.php
|-- README.md
|-- site
|   |-- assets
|   |-- config.php
|   |-- hello.css
|   |-- install
|   |-- modules
|   `-- templates
|-- vendor (3rd party vendors from PHP, Eg: Aura.Includer )
|-- httpdocs ( you can name this folder what ever you like )
|   |-- index.php
|   |-- site ( css, js and images copied from realpath )
|   `-- wire ( css, js and images copied from realpath )
`-- wire
    |-- config.php
    |-- core
    |-- index.config.php
    |-- modules
    |-- README.txt
    `-- templates-admin

You also need to change the $rootPath in index.php accordingly. Hope someone will find it useful. I am releasing it under BSD-2-Clause

Using Aura Dispatcher in Silex

2 days back Paul M Jones wrote an awesome post A Peek At Aura v2 — Aura.Dispatcher the idea behind Aura.Dispatcher and how it was born.

So today, let us try to integrate Aura.Dispatcher with Silex. This post is inspired by the comment made by Luis Cordova. Thank you.

1
2
3
composer create-project silex/silex --no-dev silexproject
cd silexproject
composer require aura/dispatcher dev-develop-2

I hope you have composer installed else get composer.

I am not going to explain each and everything, the code is self explanatory. You can move the classes according to your wish (may be to another folder). I am trying to show a simple use case.

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
48
49
50
51
52
53
54
55
56
57
58
<?php
require __DIR__ . '/vendor/autoload.php';

use Aura\Dispatcher\Dispatcher;

$dispatcher = new Dispatcher;

$dispatcher->setMethodParam('action');
$dispatcher->setObjectParam('controller');

class Blog
{
    public function browse()
    {
        // ...
    }

    public function hello($name, $app)
    {
        return 'Hello '. ucfirst($app->escape($name));
    }

    public function edit($id)
    {
        echo "Here";
        exit;
        // ...
    }

    public function add()
    {
        // ...
    }

    public function delete($id)
    {
        // ...
    }
}

$dispatcher->setObject('blog', function () {
    return new Blog;
});

$app = new Silex\Application();

$app->get('/hello/{name}', function ($name) use ($dispatcher, $app) {
    $params = [
        'controller' => 'blog',
        'action' => 'hello',
        'name' => $name,
        'app' => $app,
    ];
    $result = $dispatcher->__invoke($params);
    return $result;
});

$app->run();

See how we moved the return 'Hello '. ucfirst($app->escape($name)); to a controller and action. I haven’t used Silex extensively, so there can be better ways for integration.

Update : I was asking Beau D. Simensen on the integration, and he gave another shot.

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
// all code as same as above, upto the route

$app->get('/hello/{name}', function ($name) use ($app) {
    return [
        'controller' => 'blog',
        'action' => 'hello',
        'name' => $name,
        'app' => $app,
    ];
});

$app->on(\Symfony\Component\HttpKernel\KernelEvents::VIEW, function ($event) use ($app, $dispatcher) {
    $view = $event->getControllerResult();

    if (is_null($view) || is_string($view)) {
        return;
    }

    if ( ! is_array($view)) {
        // we can only handle array data in the view
        return;
    }

    if (! (isset($view['controller']) && isset($view['action']))) {
        // at this point we don't know what is going on.
        return;
    }

    $response = $dispatcher($view);

    if ( ! $response instanceof \Symfony\Component\HttpFoundation\Response) {
        // If the response is not a Response instance, wrap it in one
        // and assume that it was something appropriate as a response
        // body.
        $response = new \Symfony\Component\HttpFoundation\Response($response);
    }

    $event->setResponse($response);
});

$app->run();

I have purposefully kept the full path like \Symfony\Component\HttpFoundation\Response

Hope you love Aura.Dispatcher and use when you need architecural changes.

Please do take time to read Refactoring To Architecture Changes

Thank you and if you loved the post please do a tweet :–).

Happy PhPing!

REST: Is DELETE Idempotent?

This post is a thrive to learn, and not to show anyone is incorrect. Feel free to share your thoughts.

Lukas Kahwe Smith was having a nice post RESTing with Symfony2

Quoting a few words from the post on REST

DELETE and 404

I started my talk on RESTing with Symfony2 with an introduction to REST itself. On slide 7 of my talk I explained the concept of “safe” and “idempotent” HTTP methods. Many people were surprised when I explained that DELETE should be idempotent, meaning that sending a DELETE request to a resource that has been removed should infact not return a 404.

I am not a REST guru, but in fact I got curious on the same, and was looking at http status 410 Gone

@harikt 1st Q that must be answered is if DELETE is idempotent. if it is then the status code shouldn't change on subsequent delete requests — Lukas Kahwe Smith (@lsmith) October 29, 2013

What is idempotent?

Quoting from Wikipedia

Idempotence is the property of certain operations in mathematics and computer science, that can be applied multiple times without changing the result beyond the initial application. The concept of idempotence arises in a number of places in abstract algebra (in particular, in the theory of projectors and closure operators) and functional programming (in which it is connected to the property of referential transparency).

There are several meanings of idempotence, depending on what the concept is applied to:

  • A unary operation (or function) is idempotent if, whenever it is applied twice to any value, it gives the same result as if it were applied once; i.e., ƒ(ƒ(x)) ≡ ƒ(x). For example, the absolute value: abs(abs(x)) ≡ abs(x).
  • A binary operation is idempotent if, whenever it is applied to two equal values, it gives that value as the result. For example, the operation giving the maximum value of two values is idempotent: max (x, x) ≡ x.
  • Given a binary operation, an idempotent element (or simply an idempotent) for the operation is a value for which the operation, when given that value for both of its operands, gives the value as the result. For example, the number 1 is an idempotent of multiplication: 1 × 1 = 1.

Christophe Coevoet also feel the same

@lsmith then 410 is probably the best status code here, and 404 otherwise /cc @harikt @_m6w6 — Christophe Coevoet (@Stof70) October 29, 2013

Why?

@lsmith The definition says "without changing the result". the HTTP spec says that the result is the state of the app @_m6w6 @harikt — Christophe Coevoet (@Stof70) October 29, 2013

 Status code of DELETE

The above screenshot is limited, you can check all the messages passed from https://twitter.com/harikt/status/395154834426314752

Woke up early morning and I noticed a subsequent post Is a HTTP DELETE request idempotent? by Lee Davis. Interesting to read his thoughts on the same. There was a nice discussion by Jason Lotito, do consider reading it.

I felt Jason Lotito is correct.

Wikipedia has something to say aboout Idempotent methods

Hypertext Transfer Protocol Idempotent methods

Methods PUT and DELETE are defined to be idempotent, meaning that multiple identical requests should have the same effect as a single request (Note that idempotence refers to the state of the system after the request has completed, so while the action the server takes (e.g. deleting a record) or the response code it returns may be different on subsequent requests, the system state will be the same every time).

So what does that mean?

Let us look into a real world example deleting http://example.com/post/121

We send a DELETE method via REST. What is going to happen?

I am quoting from http://www.restapitutorial.com/lessons/httpmethods.html

On successful deletion, return HTTP status 200 (OK) along with a response body, perhaps the representation of the deleted item (often demands too much bandwidth), or a wrapped response (see Return Values below). Either that or return HTTP status 204 (NO CONTENT) with no response body

so far, so good.

What is going to happen on your subsequent request?

2nd time we are sending a DELETE method via REST, what do you expect to get?

204 No Content. What does that mean?

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.

No Content is a good status, which means the server has exectuted your delete operation successfully is a wrong information.

iirc I have learned in Software Engineering, the wrong information is too bad than sending an error. Eg : 5+2 returning 9. I read some where at http://www.joelonsoftware.com/ the bug they want to deal with when he was at microsoft. ( If anyone have the link please comment it)

So if you know that a request for http://example.com/post/121 is already deleted, then 410 Gone will be the right status.

If you don’t know 404 Not Found is the best status. Say it is not created, do we send 204?.

So here http://example.com/post/121 is already deleted. (That means your subsequent response should be same, note that not response status code)

It is upto your application how to deal with making it truely RESTful. Else passing false information as response always is a wrong way.

I have also tried to get RSDL (RESTful Service Description Language) Maintainer to know the real information.

Probably I am wrong, but I am still learning REST.

Thank you.

Conferences : Is It Really Worth?

What do you think, Is it really worth to go to a conference, and spend so much money?

Yes, it is really worth. You don’t know what will happen tomorrow.

These are some of the things that you can take from a conference

  • Mingle with people and get new contacts

  • Learn from the mistakes they did

  • Not re-inveting the wheels others already did

  • Who knows whether you are getting new job opportunities ;–).

  • Improve your work from the experience you learned.

I would like to give a shout at what I learned/earned going to conferences

Some of the conferences I attended are osidays 2010(as an attendee) and 2012 (as a speaker), yahoo open hack 2012, hasgeek events. Hasgeek events are one of the best events. One of the best conference I atteneded by Hasgeek is Fifth elephant. It is well organized and have strict timing. I got more interested in data mining, analysis, processing etc. Also got introduced to Hadoop and much more.

I wasn’t aware where I will be using stuffs like gearman, nltk, Elastic Search, GrayLog2, Log Stash etc. Fifth elephant and Yahoo open hack really helped me a lot to learn more about what the people at the conference is working on, what are the challenges they are facing, how they resolved etc.

If you are like me, who love to attend conference, but unable to move to the location where it is happening, then NomadPHP is looking at you. One of the good feature is you can watch the videos later (if you are unable to attend at the time). Please Thank Cal Evans for the greatest initiative.

Do attend the talk by Aura PHP guru Paul M Jones who will be speaking for NomadPHP titled A Stitch In Time Saves 9; or,Solving the N+1 Problem

Chek the site NomadPHP for more talks.

If you have a feeling like conferences just introduce stuffs, and you are left to learn from there, then you should join mastering Object Oriented PHP by Brandon Savage

There is also a great initiative by Noufal Ibrahim called The Lycaeum, you can learn some Python.

So do attend a conference, and don’t miss opportunities that are looking at you tomorrow.