What is dependency injection pattern, how to understand it?

Dependency Injection (DI) is a design pattern commonly used by many frameworks, and, is a good practice in development.

Understanding dependency injection is like a child game… really!

Let’s take an example with your phone battery. If you have an Iphone you probably have a phone integrated battery that you can’t remove, and, in many other smartphones, you have removable batteries.
All of these phones depend on a battery.

So, dependency injection is the fact of injecting any battery (dependency) in your phone without worrying about its name, its emplacement, its content. We also say that it helps reducing couplage.

Integrated batteries = no DI = high couplage.
Removable batteries = DI = low couplage.

Live example:

//No dependency injection, high code couplage
function phone (){
    $battery = new batterry();
    $battery->on();
}

//With dependency injection, low code couplage
function phone(Service $service){
    $battery = $service->get('battery');
    $battery->on();
}

Without dependency injection, your dependency is integrated inside your method, we say that the dependency and method are coupled. But, what if you need to change the battery class and what if you have dozens of methods like this? Surely you won’t want to update parts of your code everytime.

With dependency injection, you call a kind of service which is binded to a generic battery class. Everytime you’ll have to change the mother class, you’ll have to specify it in your service configuration without modifying your working code.

Edouard Kombo // @edouardkombo. Never stop learning.

What is dependency injection pattern, how to understand it?

What should you expect from php5.5 engine refactoring ?

Maybe you’ve already heard these days about actual refactoring of php 5.5 engine by Zend team.

Even if php is the world leading language for development, more and more serious players are emerging like Facebook with its HHVM.
To stay the longer in the run, it is mandatory to go further than a simple syntax release, it is important to improve performance.

If typical real-life PHP application spends about 20% of the CPU time in memory manager, 10% in hash tables operations, 30% in internal functions and only 30% in VM, the team decided to focuse on memory representation of many data types that won’t impact the all language structure.
That improved some applications performance from 10% to 30%, check this link https://wiki.php.net/phpng.

If tests have shown 20% of improvement for CMS like WordPress (v3.6), 11.7% for Drupal (v6.1), published results concern old cms versions, and like Dmitry Stogov (Mr Performance inside Zend family) said, gain in performances will strongly depend of your application.

So, we are very excited about improvements in php and we’re waiting impatiently, but, this refactoring is only a contribution and we don’t have yet the certitude it will be finally part of php.

The refactoring is still in progress but is enough advanced to test it locally on your machine.
Depending on the framework or cms you work with, you will gain in performance or not.

One advice, just wait.

 

What should you expect from php5.5 engine refactoring ?

Github – Normalize repository line endings on both unix and windows

When all the members of your team assigned to a project are working on the same OS, everything goes fine, but when they are using different OS such as Linux and Windows, you will surely encounter line endings issues in the different commits, that will degrade comparisons tasks.

The solution by example, if your production server is under linux, is to tell your developers under windows to force Github and their IDE apply “LF” line endings (if you use netbeans, check for “show and change line endings”). We will see here how to force Github using LF line endings on Windows (I assume your IDE is configured to save your files in LF line ending).

First, open your console and type

git config --global core.autocrlf false

Go to Github directory


C:\Program Files (x86)\Git\etc

//Give write permissions (if necessary) to these files and open them
.gitattributes
.gitconfig

//In .gitattributes add this line, files you will check will now be normalized
* text eol=lf

//In .gitconfig, set autocrlf to false if it hasn't been done by the previous command
//This option will not set automatically files to Crlf even if in lf before
[core]
    symlinks = false
    autocrlf = false

 

Open your console and apply the generalization to Github core

git config --global core.eol lf

 

Now, every file you will work with, will be cached and committed with LF line endings.
But, maybe you want all your repository and its branches to be updated to correct line endings, right?

Let’s do this, open your console one more time and type this:

//These commands will remove cached files and normalise the current repo branch
git rm --cached -rf .
git diff --cached --name-only -z | xargs -0 git add .

//these ones will normalize all the repo branches
git ls-files -z | xargs -0 rm
git checkout .

That’s all, you will no more have line endings issues in your project.
On the other side, make sure that new developers integrating your team will follow this process.
PS: If no changes appear, reclone your repository.

Good work guys.

Github – Normalize repository line endings on both unix and windows

Symfony2 – how to send video response to twig view

In this tutorial we will learn a very basic tip, how to send a video to twig view, through a controller.

To perform this operation, I assume (for your comfort) that you work with knpGaufretteBundle (filesystem abstraction layer) and LiipImagineBundle if you need it. If you don’t have any of these packages, still get a look to Symfony Filesystem component documentation.

We will only use Symfony based Filesystem component. Let’s see our php function

    /**
     * Respond video source to twig view
     * 
     * @param object $video Video entity object
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function videoResponse($video){
        //Target service filesystem
        $filesystem     = (object) $this->get('your_service_filesystem');
        
        //Get the video filetype
        $fileType       = (string) $video->getFiletype();
        
        //Fetch binary video content
        $content        = (string) $filesystem->read($video->getPath());
        
        return new Response($content, 200, array(
            'Content-Type'        => 'video/' . $fileType           
        ));
    }

What we’ve done here is that, we sent an http header with a content type of the video (mp4, ogg, webm…) containing the video content. When you’ll access this url, the video will be directly accessible in your browser.

In your twig, just write this:

    <video id='video' autoplay loop controls='true'>
        <source src="{{my_video_path}}"  type="video/mp4">
        <source src="{{my_video_path}}" type="video/webm">
        <source src="{{my_video_path}}"  type="video/ogg">
    </video>

 

That’s all :).

Symfony2 – how to send video response to twig view

VanillaJS framework – Tutorial

You wanna have fun, right? I’ll give you fun :).

VanillaJS is not a framework, it is your native javascript embed in your browser, everyone already use it from Google to Yahoo and Facebook and… everyone who develops with Javascript.

You wanna learn more on it? Go to official VanillaJS website (lol) http://vanilla-js.com/

That’s all guys, have fun and a great great great day :).

VanillaJS framework – Tutorial

3 reasons a good developer should start blogging

The true question is why wouldn’t you start blogging?

Blogging as a developer gives you a lot of opportunities to serve new generations and your carreer.

1. Blog what you’ve learned, blog problems and solutions

To get where you are, someone got to teach you something. This person can be a teacher or simply a person like you, who has learned something from someone else and just wanted to share his knowledge with you.
If you share what you’ve learned, someone else will always benefit from you, and will be incited when time will permit, to share himself his knowledge.
This is how works open source community.

2. Keep up to date

In order to learn something, you would have encountered some problems that needed to be solved. When you’re in a search of resolving a problem, you allow yourself to discover new practices, new methods, new languages, new opinion leaders, new frameworks… you stimulate your brain and keep up to date, and this is the unique condition to last in this work, and, maybe to become an opinion leader.

3. Your blog is your cv

Imagine you just have finished learning a new framework, and want to share one or many tutorials on it. This is an excellent way to make all your experiences in your cv be easily verified. The more you will publicly share your aptitude in new tools and methods, the more you will gain reputation.

These are quick advantages I see for developers who want blogging. There are many other advantages, but i don’t want to go further on them.

Also, a blog isn’t enough, you have to be on Github, stackoverflow, twitter or any other social network made for.

Would you now start blogging?.

Edouard Kombo // @edouardkombo. Never stop learning.

3 reasons a good developer should start blogging

AngularJS – your first Hello world tutorial

Hello there, today, we will start a basic entry to the AngularJS framework.

But, before that, I encourage you to learn the origins of the framework on Wikipedia here http://en.wikipedia.org/wiki/AngularJS, the differences between JQuery and AngularJS i have posted here https://creativcoders.wordpress.com/2014/05/11/differences-between-jquery-and-angularjs/.

This first tutorial is very simple and basic, we will just show our first “Hello world” with AngularJS, later I will show you more complex tips.

We will not use css in this example, just create a specific folder in which you will create an index.html file and a simple helloWorld.js file in a directory called “js”, like this.


js/helloWorld.js
index.html

Your index.html template must look like this:

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Angular - first hello world</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
</head>
<body>
    <!--[if lt IE 7]>
        <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
    <![endif]-->

    <section>
        <header id='header'>
            <h1></h1>
        </header>
    </section>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
    <script src="js/helloWorld.js"></script>
</body>
</html>

Ok, you see in this example that we already have included angular.js from Google and our helloWorld.js script.
Our job will be to update h1 tag and apply it a dynamic text… “Hello world!”, let’s go!

To tell AngularJS that we will work in the body, we have to decorate it with a directive called ‘ng-app’, let’s name it ‘hello’, just like this:

<body ng-app='hello'>

Then, we have to create in js/helloWorld.js, an empty ‘hello’ Angular module that will initiate angularJSin the body.

var app = angular.module('hello', []);

AngularJS now knows that we will manipulate the body with the hello module, but we want the “Hello world!”text in the h1 tag to be dynamically modified.
We will then target he head tag “section” upon h1, and decorate it with a controller directive we will name ‘helloController’, just like this.

<section ng-controller='helloController'>

Now, we will attach to hello module, a helloController.

var app = angular.module('hello', []);

//$scope means that we attach directly the view in the controller
//We will be able to do DOM manipulations with $scope
app.controller('helloController', function($scope)(){
});

Right! you know how to attach an Angular module to a body and a controller to a tag, now, we need to attach a dynamic data (model) to h1 tag.

To do this, we will work with models, models in AngularJS help you manipulate datas through ng-model directive in the view. You only have to change datas in the specified controller through the scope.

Simple example, if you have to change a tag var or an input value, you have to specified a directive called ng-model to it, and a corresponding var like this “{{myModel}}” in the value field.

Concrete example, we specify a model directive we name “welcome”.

//Like many other templating engines we use double brackets to define vars
//When defined in the controller, the var model "{{welcome}}" will be dynamically replaced
<h1 ng-model='welcome'>{{welcome}}</h1>

In the controller, we simply add this to the scope

var app = angular.module('hello', []);

//$scope means that we attach directly the view in the controller
//We will be able to do DOM manipulations with $scope
app.controller('helloController', function($scope)(){
    $scope.welcome = 'Hello World!';
});

This is how your complete html code must look like.

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Angular - first hello world</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
</head>
<!-- ng-app is a directive that specifies that we are using angular.js -->
<body ng-app='hello'>
    <!--[if lt IE 7]>
        <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
    <![endif]-->

    <section ng-controller='helloController'>
        <header id='header'>
            <h1 ng-model='welcome'>{{welcome}}</h1>
        </header>
    </section>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
     <script src="js/helloWorld.js"></script>
</body>
</html>

Congratulations, you’ve just done with success your first hello world tutorial with AngularJS, wasn’t it so simple?

More tutorials will come soon, keep in touch.

AngularJS – your first Hello world tutorial

AngularJS – Test driven development tutorial

AngularJS is a great framework that allow separation of concerns pattern, if you’re new to AngularJS, maybe you need to learn differences between JQuery and AngularJS i’ve explained here https://creativcoders.wordpress.com/2014/05/11/differences-between-jquery-and-angularjs/.

For this first tdd with Angular, we just want a simple directive to indicate in our menu what our current route is. We can declare what we want in our view:

//View in the html
//<a href="/hello">Hello</a>

//Test begins here:
it( 'should add "active" when the route changes', inject(function() {
    var elm = $compile( '<a href="/hello">Hello</a>' )( $scope );

    $location.path('/not-matching');
    expect( elm.hasClass('active') ).toBeFalsey();

    $location.path( '/hello' );
    expect( elm.hasClass('active') ).toBeTruthy();
}));

If we run our test, it will fail because initial link has no class ‘active’. We can now declare a directive to add a class on urlChange without having to modify the html.

.directive( 'whenActive', function ( $location ) {
    return {
        scope: true,
        link: function ( scope, element, attrs ) {
            scope.$on( '$routeChangeSuccess', function () {
                if ( $location.path() == element.attr( 'href' ) ) {
                    element.addClass( 'active' );
                } else {
                    element.removeClass( 'active' );
                }
            });
        }
    };
});

Well done for your first test driven development in AngularJS.

AngularJS – Test driven development tutorial

Differences between JQuery and AngularJS

Firstly you have to know that AngularJS and JQuery are different javascript frameworks, so never, never mixed up AngularJS with JQuery code. If you’re a JQuery magic developer, please invest some times in AngularJS, it will change your life.

Separation of concerns

AngularJS helps you keep your concerns separate with powerful utils (controllers, directives, models and view). The view is like a plasticine formless that you remodel through directives (DOM manipulation abstraction that help you augment your view) and models (that represent your datas), that are encapsulated in a controller linked to a specific html section. Unlike JQuery, this separation of concerns help you have testable code (remember the last time you’ve seen a jQuery plugin with unit tests).

<section id="todoapp" ng-controller='todoController'>
    <header id="header">
        <h1>TODOList</h1>
        <form id="todo-form" action="#" ng-submit='addTodo()'>
            <input id="new-todo" autocomplete="off" type="text" autofocus="" ng-model='newTodo' placeholder="{{placeholder}}" />
        </form>
        </header>
    </section>

In this code, what you see as ng-x is called a directive. ng-controller means that this section of code is related to todoController controller and the input data is specified as newTodo model (ng-model). Use of directives is also called use of decorator pattern.

Bi-directional data binding

In the previous code, modification in the view will affect the controller that can also affects the view. In the following code, when the form will be submitted, the input value will equal “Loader ended” ! it is as simple as that, how do you figure that in JQuery?

var app = angular.module('todo', []);
    app.controller('todoController', function ($scope, filterFilter, $http, $location) {
        $scope.placeholder = 'Loading...';
        $scope.addTodo = function (){
            $scope.newTodo = 'Loader ended';
        };
    };

Dependency injection

One other great tool from AngularJS is dependency injection (DI). Dependency Injection can seem very awful if you’re not familiar with back-end languages like php or Java, but it will become very useful and simple, i promise.
Dependency injection means that you have one service “A” (class that does a specific job) which needs an instance of another service “B” in order to work, we then say that we inject B into A without having to worry about loading order, or file locations, or anything like that.
DI in AngularJS will take all its sense in unit testing.

Test driven development

How many JQuery plugins have you seen, used, or written, which contained test suite? Not very many because you JQuery needs iterative development and doesn’t suit SOLID principle, but AngularJS does.
In jQuery, the only way to test a plugin is to develop a separated component with a demo page to perform DOM manipulation, and then integrate it into our application. Because of that, we opt for iterative instead of test-driven development. How inconvenient!

I’ve written an exemple of unit testing with AngularJS here https://creativcoders.wordpress.com/2014/05/11/angularjs-test-driven-development-tutorial/, have a look to.

Conclusion

Remember, AngularJS is not JQuery, don’t even include JQuery above AngularJS, it will hold you back. When you come to a problem that you think easier to solve with JQuery, try to think about how to do it within the confines the AngularJS before. If you don’t know, ask for, it will save you time, believe me.

Differences between JQuery and AngularJS

Cabin principle or how to define an object oriented code

CABIN (Concrete ABstraction of INterfaces) is just a principle sticked to the notion of object i’ve defined here https://creativcoders.wordpress.com/2014/05/05/what-exactly-is-an-object-oriented-code/ few days ago.

Let’s remind it.
I’ve defined an object oriented code like a concrete class that strictly implements interfaces and extend abstract classes.

Ok, so you’re telling us a class that doesn’t implement an interface and extend abstract classes is not really an object?
Yes, exactly, and let me explain you why.
You surely agree with me that your smartphone is simply an object that help you communicate with the world, right?
What’s really happening in this case, is that your smartphone is just a shape, an abstract shape thought by a company, and containing a complex interface that you concretely use from.

It is as simpler as that and no more complicated.
An object in the real life is only a concrete use of an abstracted shape implementing a specific interface.

The same equals for objected oriented code, then, CABIN stands for Concrete ABstract of INterfaces.

Edouard Kombo // @edouardkombo. Never stop learning.

Cabin principle or how to define an object oriented code