Hello all, in last Blog we learn about Angular.JS, today will write some code and will see how this works.

First let’s understand how Angular script works.

This is an simple example of Browser, what happen when we do request for any web page.
Browser request URL to server and Server response with HTML and JS files that loads in Browser.

browser1

Now, what if we do another request with tradition way, here we can see again.
Browser again send URL request to server and server again send HTML & JS file that entire page load again.

browser2

This is time taking, congestion in network, flickering of webpage all the time.
So we need something that loads faster without flickering and yes use low bandwidth in network.
Here comes Angular in action. we can see this picture.

angularjs

When user request 2nd times, server only send required data and that loads in to existing HTML page and pages loads faster.

How to implement this??? very simple!!!

But before writing any piece of code, we need to learn some part of Angular i.e what Angular JS consist of. Basically it consist of 5 things

:- Module
:- Controller
:- Router
:- Service
:- Dependency Injection

for basic we required only Module,Controller,Directives and Expressions.

Let’s start with Module :-

Module is like a container for the different parts of your app – controllers, services, filters, directives, etc.

var myApp = angular.module('myApp',[]);
}]);

Controller :- It is a JavaScript constructor function that is used to augment the Angular Scope.We use ng-controller directive to use controller.

ex:-

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

myApp.controller('BaseController', ['$scope', function($scope) {
  $scope.greeting = 'Hola!';
}]);

Directive :- These are various Angular defined keyword that used to take Angular in action.
ex:- ng-app,ng-controller,ng-click,ng-show etc.

Expression :- These are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }} in HTML.

ex:- {{ 1+2 }}, {{a+b}}

Now, Let’s start with simple coding.
we want to display sum of 2 number using Angular js.

Open any Editor and make HTML file let’s say angular.html and write this piece of code inside.

<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.0" src="//code.angularjs.org/1.3.0/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="myApp">
  <h1>Hello Angular</h1>
  <div ng-controller="MainCtrl">
  1st Number : <input type="text" ng-model="num1"><br/>
  2nd Number : <input type="text" ng-model="num2">
  <input type="button" ng-click="add(num1,num2)" value="ADD"><br/>
  Sum : {{result}}
  <div>
</body>

</html>

Here, we use ‘ng-app=”myApp”‘ this tells angular that within this region our angular script will work and invoke.

We also used ‘ng-controller=”MainCtrl”‘ this tells angular where controller exist and help to manipulate DOM element.

ng-model=”num1″ i.e used for holding variable value and passing to controller.
ng-click=”add(num1,num2)” i.e used to call “add()” method inside controller.

{{result}} i.e angular Expression, used how we can display result.

We are done with HTML code, create another file for JS and named it as “script.js” and write below piece of code inside.

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

app.controller('MainCtrl', function($scope) {
$scope.add=function(num1,num2)
{
  $scope.result=parseInt(num1)+parseInt(num2);
}

});

1st line define, how we write module in script and 3rd line for defining how we ca use controller.

4th line to invoke add method and return result back to HTML.

You can see, how this working on clicking here

Hmmm… Nice 🙂 Now we are done with a simple mathematical workout for getting output of two number addition using Angular JS. What we feel!! Isn’t it really easy :). Yes. it is. So, now you can change the logic a bit and can check for subtraction, multiplication, division and so on …

Thanks and hope you will like this blog 🙂

Advertisements

Hello all, in my last blog I explained about how to configure Zend2 project, in this blog will see some more setting in Module of project with code writing in Controller and View.

Let’s start….

Check for module/Application/Module.php. If not exist create it.
Open terminal(ctrl+alt+t)

sudo vim module/Application/Module.php

And write following code :-

namespace Application;
use Zend\Mvc\MvcEvent;
 
class Module
{
    public function onBootstrap(MvcEvent $event)
    {
        $app = $event->getApplication();
        $eventManager = $app->getEventManager();
        $moduleRouteListener = $app->getServiceManager()
            ->get('ModuleRouteListener');
        $moduleRouteListener->attach($eventManager);
    }
 
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }
 
    public function getControllerConfig()
    {
        return [
            'invokables' => [
                'Application\Controller\Index' => 'Application\Controller\IndexController'
            ],
        ];
    }
 
    public function getAutoloaderConfig()
    {
        return [
            'Zend\Loader\ClassMapAutoloader' => [
                __DIR__ . '/autoload_classmap.php'
            ]
        ];
    }
}

check for module/Application/autoload_classmap.php. If not exist
create it. Open terminal(ctrl+alt+t)

sudo vim module/Application/autoload_classmap.php

And write following code :-

<?php
return [
    'Application\Module'                        => __DIR__ . '/Module.php',
    'Application\Controller\IndexController'    => __DIR__ . '/src/Application/Controller/IndexController.php',
];

We have only two classes in this module our ‘Module.php’ and ‘IndexController.php’ and now these files will autoload.

Now, last file we need to modify is config/application.config.php

sudo vim config/application.config.php

And write following code :-

<?php

return [
    'modules' => [
        'Application',
    ],
    'module_listener_options' => [
        'module_paths' => [
            './vendor',
            './module',
        ],
        'config_glob_paths' => [
            'config/autoload/{,*.}{global,local}.php',
        ],
    ],
    'service_manager' => [
        'invokables' => [
            'ModuleRouteListener' => 'Zend\Mvc\ModuleRouteListener',
        ],
    ],
];

Now, all setting are done so we can start code to Controller.
now we need to write action in it
open it in editing mode.

sudo vim module/Application/src/Application/Controller/IndexController.php

And write following code in it :-

<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        return new ViewModel();
    }
}

Now, we need to create view for this, So open terminal and create a view.

mkdir -p module/Application/view/application/index/index.phtml

Open it in editor

sudo vim module/Application/view/application/index/index.phtml

And now,write following code:-

<?php 
echo "Hello World"
?>

Now, we are all done. To check everything is working open browser and type zf2.localhost.com will get “Hello World” on webpage.

Hi all, in my last blog I explained how to “Install Zend framework 2 in Linux”.
Now, I am try to explaining how we can write code in Zend Framework 2.

After installing Zend Framework 2, Project folder structure will look like below

zf2-demo
|--config
|  |--aplication.config.php
|  |--autoload
|     |--global.php
|--module
|  |--Application
|     |--config
|     |  |--module.config.php
|     |--src
|     |  |--Application
|     |     |--Controller
|     |        |--IndexController.php
|     |--view
|     |  |--application
|     |     |--index
|     |     |  |-index.phtml
|     |     |--error
|     |     |  |--404.phtml
|     |     |  |--index.phtml
|     |     |--layout
|     |     |  |--layout.phtml
|     |--autoload_classmap.php
|     |--Module.php
|--public
|  |--.htaccess
|  |--index.php
|  |--css
|  |--js
|  |--img
|--vendor
|  |--autoload.php
|  |--bin
|  |--composer
|  |--zendframework
|--composer.json
|--composer.lock 

Now, we need to modify 3 files in setting.
1. zf2-demo/public/.htaccess (if not present create it)
2. zf2-demo/public/.index.php
3. zf2-demo/config/application.config.php

Open first file i.e .htaccess in terminal (ctrl+alt+t)

  sudo vim zf2-demo/public/.htaccess
 

Now, overwrite .htaccess file with following code :-

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Save it and open index.php and overwrite with following code:-

<?php
chdir(dirname(__DIR__));

// Setup autoloading
require 'init_autoloader.php';

// Run the application!
Zend\Mvc\Application::init(require 'config/application.config.php')->run();

Save it and open config/application.config.php and overwrite following code :-

<?php
return array(
    'modules' => array(
        'Application'
    ),
    'module_listener_options' => array(
        'config_glob_paths'    => array(
            'config/autoload/{,*.}{global,local}.php',
        ),
        'module_paths' => array(
            './module',
            './vendor',
        ),
    ),
);

Check for local.php and global.php
if they don’t exist create them as shown above in folder structure with
following code.

<?php
return [
];

That’s all for setting up, now we need to write code for Module.
Open module/Application/config/module.config.php and write the following code.

<?php
return [
    'router'    => [
        'routes' => [
            'home' => [
                'type'      => 'Literal',
                'options'   => [
                    'route'     => '/',
                    'defaults'  => [
                        '__NAMESPACE__' => 'Application\Controller',
                        'controller'    => 'Index',
                        'action'        => 'index',
                    ],
                ],
            ],
        ],
    ],
    'navigation' => [
        'default' => [
            'home' => [
                'label' => 'Home',
                'route' => 'home'
            ],
        ],
    ],
    'view_manager'  => [
        'doctype'                   => 'HTML5',
        'display_exceptions'        => true,
        'exception_template'        => 'error/index',
        'display_not_found_reason'  => true,
        'not_found_template'        => 'error/404',
        'template_map'              => [
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
            'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
        ],
    ],
];

Now, we are done with the initial set-up of project using Zend Framework 2. In my next blog we will go through the actual code which will print “Hello World” for us, the reason we are reading this post.

As many of us know about ZF2 (Zend Framework 2), it is an open source, object oriented Framework designed for developing web applications and services using PHP 5.3+. So, in this post we will go through the installation process for ZF2 Framework with a skeleton application so that it will be easier for the developer to continue developing the application directly :). first we need to create public folder to handle all project. Open Terminal or ctrl+alt+t and type following commands.

mkdir public

Now we need to create project folder inside public folder.

mkdir public/zf2-demo

Now we need to go inside our project folder.

cd public/zf2-demo

We required Just 4 basic steps to install ZF2:- STEP 1:- Now we have 2 option to install Zend Framework 2 in our project folder. Option 1 :- Go to here and download the zip file. Go to here and download the tgz file. Simply unpack inside project folder. Option 2:- Use Composer to install Zend Framework 2. you can get composer from here. Here you have option to download and use composer or you click “getting started” and get details.

"repositories": [
    {
        "type": "composer",
        "url": "https://packages.zendframework.com/"
    }
],

You can then add any of our packages to your require list.:

"name" : "ZF2 demo",
  "require" : {
    "zendframework/zendframework" : "2.3.*"
},

Run the install command to resolve and download the dependencies:

$php composer.phar install

Installed Zend Framework! It will be in a new folder called “vendor” this is where composer installs all dependent libraries. STEP 2:- Now we need to configure Apache server Setup To use Apache, setup a virtual host. Open terminal or ctrl+alt+t and type

cd etc/apache2/sites-available
sudo vim 000-default.conf

Edit it and it should look like following.

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName zf2.localhost.com
        ServerAlias zf2.localhost.com
        DocumentRoot /var/www/html/zf2-demo/public

   <Directory /var/www/html/zf2-demo/public>
       AllowOverride All
       Order allow,deny
       Allow from all
   </Directory>
</VirtualHost>

Or, if you are using Apache 2.4 or above:

<VirtualHost *:80>
   ServerAdmin webmaster@localhost
        ServerName zf2.localhost.com
        ServerAlias zf2.localhost.com
        DocumentRoot /var/www/html/zf2-demo/public

   <Directory /var/www/html/zf2-demo/public>
       AllowOverride All
       Require all granted
   </Directory>
</VirtualHost>

STEP 3:- Open .htaccess file inside project/zf2-demo/public and override it with following code.

RewriteEngine On
# The following rule tells Apache that if the requested filename
# exists, simply serve it.
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
# The following rewrites all other queries to index.php. The
# condition ensures that if you are using Apache aliases to do
# mass virtual hosting, the base path will be prepended to
# allow proper resolution of the index.php file; it will work
# in non-aliased environments as well, providing a safe, one-size
# fits all solution.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]

STEP 4:- open URL zf2.localhost.com it will open like zend now, you are now ready with ZF2. Enjoy coding!!!

 

What is Angular JS?
AngularJS is an open-source web application framework, maintained by Google and community, that assists with creating single-page applications, which consist of one HTML page with CSS, and JavaScript on the client side. It extending HTML into a more expressive and readable format.It decreases emphasis on directly handling DOM manipulation from the application logic, allowing for easier testing.
It employs efficient two-way data binding and sensible MVC implementation, reducing the server load of applications. It features directives, which are incredibly robust tools that are significant contributors to Angular’s ubiquity.
AngularJS is self-described as ‘HTML enhanced for web apps’.

Things to know before staring with Angular Js
1. A very basic knowledge of HTML
2. Knowledge of JS and it’s syntax.
3. Desire to learn Angular

Why to use Angular.js?
Now a days we have so many JS framework we have, but why to choose Angular??
Here we have answer.

1. MVC.
Most frameworks implement MVC by asking you to split your app into MVC components, then require you to write code to string them up together again. That’s a lot of work. Angular implements MVC by asking you to split your app into MVC components, then just let Angular do the rest.

2. A declarative user interface.
Angular uses HTML to define the app’s user interface. HTML is a declarative language which is more intuitive and less convoluted than defining the interface procedurally in JavaScript.

3. Contains Directives.
Angular Directives add more functionality to the simple HTML. Directives help to enable the developer to specify custom and reusable HTML tags that change the behavior of some elements.

4. Easy DOM manipulations.
AngularJS keeps DOM manipulation codes inside the directives and not in the view. This augments in generating a clean and clear user interface.

5. Test-ready.
The fact that AngularJS comes linked with Dependency Injection (DI) makes it ready for unit testing by injecting mock data into controller and measuring the output and behavior.

6. Write less code.
All the points up till now mean that you get to write less code.

When not to use Angular?
1. Difficult to adapt the existing code :- AngularJS requires the developer to re-implement the entire transformation code which makes it extremely hard to play around while adapting existing code.

2. Too heavy :- AngularJS is a bulky framework that might be a good option to build large applications. But in case of simpler requirements of data binding, it can get a little too much to deal with and could confuse you with an excess of functionality that might be totally useless. Lighter frameworks like KnockoutJS or BackboneJS might be a better option in such a situation.

Requirement to use Angular JS
1. Angular.js Local
or Angular.js CDN  that’s it, right!!
download any and you are all ready to use Angular.

Conclusion
It’s a complete client-side solution.
Angular is not a single piece in the overall puzzle of building the client-side of a web application. It handles all of the DOM and AJAX glue code you once wrote by hand and puts it in a well-defined structure. This makes Angular opinionated about how a CRUD application should be built. But while it is opinionated, it also tries to make sure that its opinion is just a starting point you can easily change. Angular comes with the following out-of-the-box:

Data binding, as in {{}}.
DOM control structures for repeating/hiding DOM fragments.
Support for forms and form validation.
Attaching code-behind to DOM elements.
Grouping of HTML into reusable components.

 Sites build on Angular
Crunchinator
Zaptravel
Localytics
Goodfil
Mallzee