Friday, December 25, 2015

How to get end user's details in jquery

Get end user's details in jquery:

For getting all the details of any user who is using your website we have to use the following trick:

In this details we can get user's
country name,
city name,
region name,
latitude,
longitude,
ip address,
country code.

For this firstly we have to include jquery library which you can include from here.

Now write this function:



function goToPage() {
    jQuery.ajax({
        url: '//freegeoip.net/json/',
        type: 'POST',
        dataType: 'jsonp',
        success: function (location) {
            var ip=location.ip ;

            var country=location.country_name;
            var country_code= location.country_code;
            var city= location.city ;
            var region=location.region_name;
            var lat= location.latitude;
            var lng=location.longitude;
        }
    });
}



You can use this function where you want.

Thanks

Friday, December 18, 2015

Modify Laravel 5.1 Request Data before validation

Modify Laravel 5.1 request data before validation:

1. Replace All request data
Use replace() function to change all requested data with given data
 For example
$request contains first_name, last_name field.
and we want to create one filed name with combination of first_name and last_name



$newRequest = array('name'=>$request->first_name.$request->last_name);
$request->replace($newRequest);
now $request contains name field.


2. Modify Request field data.
Use merege() function to modify  requested data with given data
For Example
$request contains name field with null value .
and we want to change null to empty string.
$newRequest = array('name' => '');
$request->merge($newRequest);

-Thanks

Friday, December 4, 2015

Problem with laravel save method

Problem with laravel save method:

Laravel save() method save data to database and return inserted data with inserted id . when we save another record after one using same object it  overwrite first record instead of creating new record .
Example

1. create AbcModel.php

public function Abc extend Model{

   public function createNew($data){
       $this->abc_id = $data->id;
        $this->name = $data->name;
     
   }
}
Note : Model Abc only save first record of $users array and in second times it update first record data with second record without creating second record in table.

Solution of above problem is create object of Abc Model inside createNew() method .

public function Abc extend Model{

   public function createNew($data){
    $abc = new Abc();
       $abc->abc_id = $data->id;
        $abc->name = $data->name;
     
   }
}


2. create AbcController.php
class NotificationController extends BaseController {

     public function createAbc (){
       
        $users = array(0 =>array('id' => '1','name'=>'Ravi')
                                  1 => array('id' => '2','name'=>'Ranjan'));

      $new = new Abc();
      foreach($users as $user){
           $new->createNew($user);
        }
     }

}

Friday, November 13, 2015

Multipule table authentication using laravel 5.1

 Multipule table authentication using laravel 5.1:

1. Install laravel 5.1
2.Open terminal and go to laravel instalation folder.
3.Run the following command.
composer require sarav/laravel-mltiauth dev-master
4.Open config/app.php
Replace Illuminate\Auth\AuthServiceProvider:: class with Sarav\Multiauth\MultiauthServiceProvider

5.Modify auth.php
'multi' => [
    'user' => [
        'driver' => 'eloquent',
        'model'  => App\User::class,
        'table'  => 'users'
    ],
    'admin' => [
        'driver' => 'eloquent',
        'model'  => App\Admin::class,
        'table'  => 'admins'
    ]
],
6. Create admins table
7.login using follwing details.
\Auth::attempt("user", ['email' => 'johndoe@gmail.com', 'password' => 'password']);

// Attempts to login admin with email id johndoe@gmail.com
\Auth::attempt("admin", ['email' => 'johndoe@gmail.com', 'password' => 'password']);

Friday, November 6, 2015

Login after admin approval in Laravel 5.1

Login after admin approval in Laravel 5.1:

In Laravel 5.1, here is a system that when we register any user then it's by default logged in. If we want to make a system in which we are in need of admin approval then we have to make it like the following code:

Login after admin approval in Laravel

We have to override two method for this:

1. postLogin
2. postRegister


Open your this file app/Http/Controllers/Auth/AuthController.php

and add these functions.

Login after admin approval in Laravel


    public function postRegister(Request $request)
    {
        $validator = $this->validator($request->all());
        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }
        $this->create($request->all());
        return redirect('/auth/login')->with('status', 'Successfully Registered! You can login after the approval of admin.');
    }



Login after admin approval in Laravel

    public function postLogin(Request $request)
    {
        $this->validate($request, [
            $this->loginUsername() => 'required', 'password' => 'required',
        ]);

        $throttles = $this->isUsingThrottlesLoginsTrait();

        if ($throttles && $this->hasTooManyLoginAttempts($request)) {
            return $this->sendLockoutResponse($request);
        }

        $credentials = $this->getCredentials($request);
        $credentials['status'] = 'active';

        if (Auth::attempt($credentials, $request->has('remember'))) {
            return $this->handleUserWasAuthenticated($request, $throttles);
        }

        if ($throttles) {
            $this->incrementLoginAttempts($request);
        }

        return redirect($this->loginPath())
            ->withInput($request->only($this->loginUsername(), 'remember'))
            ->withErrors([
                $this->loginUsername() => $this->getFailedLoginMessage(),
            ]);
    }


Login after admin approval in Laravel



In postRegister() function there will only registration is possible & in postLogin() we will firstly check its status.


Here in this function $credentials['status'] = 'active' will check if its approved by admin or not.

Here status is my field name in users table and active is its value.

This will work.

Thanks

Friday, October 30, 2015

How to create name based subdomain in apache2 conf.

Create name based subdomain in apache2 conf.:

Some or many time we need to set the same document root for all or almost
each sub domains to a same document root, we can simply do it with apache virtual host  setting as following.

For say if we want that all sub domains of example.com should be hosted on same server and share the same document root then we can use apache web server's ServerAlias Directive as follows

Open this file: /etc/apache2/sites-enabled/000-default.conf

and set this code:


<VirtualHost *:80>
ServerName example.com
ServerAlias server server2.domain.com server2
ServerAlias *.example.com
</VirtualHost>
 

Thanks

Friday, October 23, 2015

How to deploy an ionic app on heroku?

Deploy an ionic app on Heroku:

For deploy your project on heroku as a serving host we can do the following

steps:

1:- At first create a heroku account and install Heroku Toolbelt on your ubuntu system as  directed in following link

https://toolbelt.heroku.com/debian

2. Now initialize a git repository and commit all code to it

as following

git init



3. add heroku remote as following

heroku login

heroku create appname

it gives you back a git and heroku serve url on successful creation.


4. Now go to your terminal and reach to project root you want to deploy on

heroku install any dependencies needed to deploy for example if it a ionic app

as per my case we need to do as follows

npm install express --save

and create the following files

a app.json and write the following code

{

    "name": "app name",

    "description": "App description",

    "repository": "heroku serve url",

    "keywords": ["Keyword1", "Keyword2", "Keyword3"]

}


and a server.js and write the following code to serve node application

var express = require('express'),

    app = express();

app.use(express.static('www'));

app.set('port', process.env.PORT || 5000);

app.listen(app.get('port'), function () {

    console.log('Express server listening on port ' + app.get('port'));

});

and some other dependencies as well should be installed first.

5. Now do the following

git commit -am"comment for version"

git push heroku master

as heroku is the remote name by default created by heroku on app creation

and master is the default git branch.

Got to tour app serve url and check for it.

Thanks

Friday, October 16, 2015

Route Model Binding using laravel 5.1

Route Model binding using Laravel 5.1:

What is Route Model Binding in laravel?
Ans: Laravel model binding provides a convenient way to inject class instances into  routes. For example, instead of injecting a user's ID, you can inject the entire User class instance that matches the given ID.

1. Open route.php and write following code .

Route::model('users', 'User');
Route::bind('users', function($value, $route) {
    return App\Task::whereSlug($value)->first();
)};
Route::resource('users', 'UsersController');

 Note: where User is Model name 

2. use users/{slug} as url instead of users/{id}

3. use controller method update({slug}) instead of update({id})

Thanks

Friday, October 9, 2015

How to send email through terminal in ubuntu?

Send email through terminal in ubuntu:

Hi everybody,

In this blog we will cover email sending through terminal in ubuntu.

1. For send a email through terminal firstly install the postfix using this

sudo apt-get install postfix
 
2. Now go to this file

sudo nano /etc/postfix/main.cf

and change

myhostname = example.com

3. Put in name of your domain into myhostname.

4. If you want to have mail forwarded to other domains, replace alias_maps with virtual_alias_maps and point it to /etc/postfix/virtual.

virtual_alias_maps = hash:/etc/postfix/virtual

5. The rest of the lines are set by default. Save, exit, and reload the configuration file to put your changes into effect:

sudo /etc/init.d/postfix reload

6. Now run this for checking through terminal

sendmail sample-email@example.org

Wednesday, September 23, 2015

Use Web Socket for Chat in Laravel 5 (Using Ratchet for particular user )

Use Web Socket for Chat in Laravel 5 step by step:

If you want to create a chat server for particular user in Laravel 5, then this blog will help you. Its a very easy and fast way to use web socket.

For this firstly you have to install Ratchet package in your application.

Step1:
For this open your composer.json and write this code in "require" key:

"cboden/ratchet": "0.3.*"

Now open open your terminal and go to your root path and run this command

composer update

It will install this package in your application.

Use Web Socket for Chat in Laravel 5


Step2:

Now create a controller and write functions on it , also include the package files.
For this , just go to your terminal and write this command:

php artisan make:controller ChatController


Now go to this file and write the following code on it:

<?php
namespace App\Http\Controllers;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class ChatController implements MessageComponentInterface
{
    protected $clients;
    private $subscriptions;
    private $users;

    public function __construct()
    {
        $this->clients = new \SplObjectStorage;
        $this->subscriptions = [];
        $this->users = [];
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        $this->users[$conn->resourceId] = $conn;
    }

    public function onMessage(ConnectionInterface $conn, $msg)
    {
        $data = json_decode($msg);
        switch ($data->command) {
            case "subscribe":
                $this->subscriptions[$conn->resourceId] = $data->channel;
                break;
            case "message":
                if (isset($this->subscriptions[$conn->resourceId])) {
                    $target = $this->subscriptions[$conn->resourceId];
                    foreach ($this->subscriptions as $id=>$channel) {
                        if ($channel == $target && $id != $conn->resourceId) {
                            $this->users[$id]->send($data->message);
                        }
                    }
                }
        }
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        unset($this->users[$conn->resourceId]);
        unset($this->subscriptions[$conn->resourceId]);
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
?>

Use Web Socket for Chat in Laravel 5

Now you have done all the functionality. Now you'll be in need of create a chat server .

Step3:

For create a chat server , go to your root path and create a file with named php_chat_server.php


write the following code in this file:

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Http\Controllers\ChatController;

require  'vendor/autoload.php';


$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new ChatController()
        )
    ),
    8080
);

$server->run();
?>



Use Web Socket for Chat in Laravel 5

Now you have to create a chat server.
You are done now.

Step4:

Now go to your root path and run this command:

php php_chat_server.php

This will start your chat server .

Step5:

For checking your working code, you have to go to your browser and open your localhost

For test you have to open two browser for this:

Now open your console in both browser and write this:

var conn = new WebSocket('ws://127.0.0.1:8080');

and then press enter

Use Web Socket for Chat in Laravel 5


same like this write the following lines and enter in both browser:

conn.onopen = function(e) {
  console.log("Connection established!");
};



conn.onmessage = function(e) {
  console.log(e.data);
};



conn.send(JSON.stringify({command: "subscribe", channel: "mychannel"}));

Now in only one browser's console write this code

conn.send(JSON.stringify({command: "message", message: "this is message"}));

You'll see this message at 2nd browser.

Use Web Socket for Chat in Laravel 5


You are done.

Thanks

Friday, September 18, 2015

Social site Authentication (signup and signin) in Laravel 5

Social site authentication (sign up and sign in ) in Laravel 5:

Social site Authentication (signup and signin) in Laravel 5

In this blog we are authenticate the users by twitter, facebook, google etc.
We can login and registration via using these account in our Laravel 5 app.
   
Social site Authentication (signup and signin) in Laravel 5

 1) Include package :- First we need to include socialite package to get started with Socialite, for include the package go to your composer.json file and below code to require section :-


"laravel/socialite": "~2.0"

Example :- so now your file code of require section looks like:-

"require": {
   "laravel/framework": "5.0.*",
   "laravel/socialite": "~2.0"
},


2) Register provider and facades :- to register provider you need to add this Laravel Framework Service Providers list. for this go to config/app.php and add below code to “providers” array to further use:


'Laravel\Socialite\SocialiteServiceProvider',
Example :- so now your file code of provider array section looks like:-



'providers' => [
   /* more already here */
  'Laravel\Socialite\SocialiteServiceProvider',


Facades :- To register facades go to config/app.php and add below code to “aliases” array :


'Socialize' => 'Laravel\Socialite\Facades\Socialite',
Example :- so now your file code of aliases array section looks like:-


'aliases' => [
   /* more already here */
  'Laravel\Socialite\SocialiteServiceProvider',


3) Get package from remote :- Now after add packages we need to install Socialite package in our application for this you need to run composer update command. for this pick up your laravel application directory path in CLI or terminal and run.

composer update
After install Socialite packages successfully we need to setup oauth providers credentials, routes and controllers

4) Setup OAuth providers credentials :- Now we need to create OAuth applications on providers like facebook, google, twitter, github etc. to get client id and client secret which need to authenticate with providers.
After getting client id and secret we need to setup credentials. To setup OAuth providers credentials go to config/services.php and add your provider config to existing “return” array like below



'github' => [
    'client_id' => 'your-github-app-id',
    'client_secret' => 'your-github-app-secret',
    'redirect' => 'http://your-callback-url',
],

Note:- for all provider add configuration(client id, client secret and redirect) for others like ‘facebook’, ‘google’, ‘twitter’.

5) Routes :- Now You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. so add routes in app/Http/routes.php like :-


// Redirect to github to authenticate
Route::get('github', 'AccountController@github_redirect');
// Get back to redirect url
Route::get('account/github', 'AccountController@github');

6) Controller :- so according to routes you need to set your controller function and make social authentication with use of facades like


public function redirectToProvider() {
  return Socialize::with('github')->redirect();
}


public function handleProviderCallback() {
  $user = Socialize::with('github')->user();
}

7) Retrieve user details :- After get success authenticate you can get all user details with $user object like


$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();

Now you have successfully setup-ed social authentication in laravel 5 using laravel socialite. Below we see an example of github social authentication.

Thanks

Friday, September 11, 2015

How to customize laravel 5.1 default error page

Customized Laravel 5.1 default error page:

customize laravel 5.1 default error page


For customized Laravel 5.1 default error page, we have to modify following file.

app/Exceptions/Handler.php

customize laravel 5.1 default error page


 By modification this file we can override this file :

convertExceptionToResponse

customize laravel 5.1 default error page
customize laravel 5.1 default error page
customize laravel 5.1 default error page


<?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\Debug\ExceptionHandler as SymfonyDisplayer;

class Handler extends ExceptionHandler
{
    /**
     * Convert the given exception into a Response instance.
     *
     * @param \Exception $e
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function convertExceptionToResponse(Exception $e)
    {
        $debug = config('app.debug', false);

        if ($debug) {
            return (new SymfonyDisplayer($debug))->createResponse($e);
        }

        return response()->view('errors.default', ['expection' => $e], 500);
    }
}


customize laravel 5.1 default error page


Due to doing this, we can easily modify this file :

errors.default

which is exist here:

resources/view/errors

Thanks

Friday, September 4, 2015

How to create database backup to dropbox in laravel 5

Create database backup to dropbox in Laravel 5:

For creating a database backup ,
Firstly you'll in need of pull the package through command line:


composer require backup-manager/laravel



Now we will need of pull dropbox adapter

composer require league/flysystem-dropbox

Now goto config/app.php this file & write this in providers

BackupManager\Laravel\Laravel5ServiceProvider::class,


And then publish the storage configuration file:

php artisan vendor:publish --provider="BackupManager\Laravel\Laravel5ServiceProvider"



Now Create a dropbox API

database backup to dropbox in laravel 5
For creating this, select dropbox api app as shown in image, then select 'yes' in drop box & enter application name and create app.

database backup to dropbox in laravel 5

Now in setting page you can see app key and app secret. Also genrate a access token on this page.

Now goto backup-manager.php file and add the below content.


'dropbox' => [
    'type' => 'Dropbox',
    'token' => 'your-token-here',
    'key' => 'your-key-here',
    'secret' => 'your-secret-here',
    'app' => 'your-app-name',
    'root' => '/backups',
],


 It will store backup in backups folder
database backup to dropbox in laravel

For testing this on your app, run this command on your terminal

php artisan db:backup --database=mysql --destination=dropbox --destinationPath=`date +\%s`-laravel4.sql --compression=null

 To check the file in dropbox, go to app folder.

Thanks


Tuesday, August 25, 2015

Zurich Insurance Group proposes 8.8 billion usd takeover of RSA Insurance Group

Zurich Insurance Group v/s RSA Insurance Group:

Swiss insurance company, Zurich Insurance Group Ltd, made a takeover proposal for British insurance company, RSA Insurance Group on Tuesday. The amount is $8.8 billion. This is the Europe's biggest insurance deal.
Zurich Insurance Group
Zurich Insurance Group

Zurich Insurance Group Ltd is Switzerland's largest insurer.As of 2013, the group was the world's 75th largest public company according to Forbes' Global 2000s list and in 2011 it ranked 94th in Interbrand's top100 brands. Zurich employs around 60,000 people serving customers in more than 170 countries and territories around the globe.

RSA Insurance Group
RSA Insurance Group

Zurich said a month ago it was weighing a bid but left it to the last day under British takeover rules to unveil a cash offer of 550 pence per share, roughly in the middle of the price range expected by investors in Zurich and RSA.


RSA said it planned to recommend the proposal to its board and gave Zurich another four weeks to come up with a firm takeover offer, though the Swiss insurance company reserved the right to ultimately bid below 550 pence per share.
Zurich Insurance Group
Zurich Insurance Group

This is the same deal as Aviva's takeover the Friends Life insurance.


Zurich, which has said it would not overpay and is seeking a return on any investment in RSA of at least 10 percent, said it had reached a “common understanding” with RSA on how the British general and commercial insurer values itself.

RSA, known for its “More Than” home and car insurance brand in Britain, is in the early stages of a turnaround under former RBS boss Stephen Hester.

Let's see, Zurich will take over or not.

Add comments about your views.

Thanks

Sunday, August 23, 2015

Indian rupee down of 66.49 against United States Dollar, lowest in two years

Indian rupee down against United States Dollar, lowest in two years:


The rupee opened at fresh two-year lows on Monday morning, trading at 66.42 a dollar or 0.90% weak on the Interbank Foreign Exchange, a level it hasn't seen since September 2013.



A strong dollar demand from importers and banks, and heavy losses in domestic equity markets weighed on the local currency, forex dealers said.

The rupee has been under pressure since China devalued its currency by nearly 5% in three tranches in an attempt to make its exports more competitive in the global market. Since then, the rupee has been tied down by excess demand for the greenback from exporters and sustained capital outflows from foreign funds.

Indian rupee down of 66.49 against United States Dollar, lowest in two years
The Sensex opened over 600 points down in early trade, and  was later trading down 841 points. All Nifty stocks in the red, tracking a major sell-off in the global markets. The fall has been triggered by a massive sell-off in the global markets on Monday.


The rupee had lost 29 paise to close at two-year low of 65.83 against the US dollar on Friday on high demand for greenback from banks and importers.




Meanwhile, the benchmark BSE Sensex tanked 1,006.54 points, or 3.67%, to 26,359.53 in opening trade.

Thanks

How is the cyber city Gurgaon (current condition of cyber city Gurgaon)?

Cyber city Gurgaon:

Gurgaon is situated in the north of India. Currently its a part of NCR. Its also known as cyber city, because Its a hub of IT work of north India.

How is the cyber city Gurgaon (current condition of cyber city Gurgaon)
In last few years, Gurgaon is growing rapidly. More than 250 (over half) of the global Fortune 500 companies either have their India headquarters or their important offices in Gurgaon. These include firms such as Walmart, Shell, Microsoft, Samsung, GM, GE, PepsiCo, Coca Cola, Google, Toyota and Facebook.

Currently condition of Gurgaon:

No doubt, Gurgaon is growing very fast also generates Rs 16,500 crore of tax revenue for Haryana’s exchequer. But its matter what's its current condition.
I am describing its current condition here:


Roads in Gurgaon: 

If you are living or working in Gurgaon, then you must know about the roads of Gurgaon. You can see NH8 (the most famous Delhi-Jaipur Highway) here. Also, you can see its parallel road (old Delhi-Gurgaon road).


How is the cyber city Gurgaon (current condition of cyber city Gurgaon)
NH8

How is the cyber city Gurgaon (current condition of cyber city Gurgaon)
Old Delhi Gurgaon Road
Both the roads are connecting to Delhi. You can differentiates by watching the pics.

- First one is 8 Lane, also having service lane.
- Second one is 4 Lane, also having mini swimming pool for frogs. 

But the matching point is:

- There are a lot of jam on them. Mostly on weekdays (Mon-Fri) at 8AM - 10AM & 6PM - 8:00PM. If there is a rain in Gurgaon, then there is surely a heavy jam for undefined time period.

In Udhog Vihar (Also a big IT hub) you can see speeding Porsches and scrambling pigs share the same streets that are invariably unlit and pockmarked with potholes.

Sometimes you have to spend 45-50 minutes to cover a 2 KM distance for your office on your two wheeler. If you are thinking you can cover this distance using your feet for save time in jam, then you are wrong. Because, either there is no footpath or you'll see other two wheeler on footpath. For live example, goto Hanuman Mandir Chowk at 9:15AM. LOLZ

There are a lot of main holes are open on the roads. No one knows, when you'll be invited for a party with cockroaches.

I have traveled to Mumbai last month. I rode my friend's apache for 1 week.
It was a rainy season in Mumbai. Mumbai's population is many times as compare to Gurgaon. Even that was a rainy season, still there was no such jam as in Gurgaon.


Environment in Gurgaon:

As Gurgaon is situated in north india, also close to Rajsthan, then its environment is hot. Its average temperature in summers is nearby 38-40 degree celsius and in winters is nearby 8-12.

How is the cyber city Gurgaon (current condition of cyber city Gurgaon)

As there are a lot of traffic problem in Gurgaon, there are a lot of pollution. Air pollution levels rival neighbouring Delhi’s (which is the worst in the world) in a city that has just a tenth of the population.

There is dust every where. You can save your money, just move on roads instead of  buying a body powder.

Basic needs in Gurgaon: 

Gurgaon’s streets are unplanned, unnamed and, in many instances, unnavigable; electricity for most hours of the day has to be generated by residents, offices and malls (there are 35 of those in the city) using their own captive generator sets that burn diesel for fuel; there is no public transport system worth mentioning that functions within the city; policing standards are akin to those of a village thana. There is no security system in nights, specially for women.


Water logging system:

Another pic of NH8


As you can see this pic, this is the water logging system of Gurgaon. It can happen on any road with the couple of hours rain. Its an example of NH8. Now you can assume any another road condition in rains.

Cost of living:

Gurgaon is just nearby Delhi. Still the rate difference in basic things are very high. It may be in case of petrol, grocery, rent, transport, electricity. If i compare Gurgoan with Delhi, then in every basic things which i mentioned are costly in Gurgaon.

How is the cyber city Gurgaon (current condition of cyber city Gurgaon)

The problem with Gurgaon is that it has grown haphazardly in the absence of any semblance of urban planning.

According to a senior Haryana bureaucrat, there never was a master plan for Gurgaon’s growth and there still isn’t one.

A master plan, among other things, demarcates zones for commercial, residential and other use and for civic infrastructure. Gurgaon has had none of that.



When a new commer comes in my office from out side of Gurgaon and after living a couples of week here, he started to complain about Gurgaon with saying that Gurgaon is consider as "Newyork of India" in his hometown, then everyone laughs at him saying that "Tera b kat dia".

Thanks

Friday, August 21, 2015

What is Red Green Refactor in Laravel?

Red Green Refactor in Laravel:

Red Green Refactor is used for testing purposes in Laravel. Stay flexible with the IoC container, and run your tests with PHPUnit.

What is the right reason? Well, that depends entirely on your circumstances and the code that you are writing and testing. 





Red: For The Right Reasons

Red should happen because the conditions of the test were not matched… not for any other reason. As one example: this means that if you are expecting an interface method to be called, the test should fail because the method was not called. It should not fail for any other reason.

An null reference exception is usually not the right reason. There are times when checking null or not-null is the right thing to do, but you should not be getting exceptions to tell you whether its null or not… most of the time, anyways. There’s some exceptions to this, of course.

A “Throw NotImplementedException();” is never the right reason. No, I do not want to throw an exception from that method that I just generated. I want it to be empty, or return a null or some other default value if there is a return type. (and yes, i know there is an option for this in Resharper… but i’ve never seen that option work, no matter how many times i’ve tried to make it work).

There are plenty of other bad reasons for red, and each specific test has to be evaluated to understand the right reason for red. Context truly is king.


Green: For The Right Reasons

A test should pass not just because the conditions stated in the assertions exist, but because the simplest thing that could possibly meet the requirements was implemented.

Back when I was doing all state based testing, I would often make my test go “green” by hard coding a value into it. For example, if I was asserting that the output of some calculation was supposed to be 60, I would hard code a “return 60;” in the method that was being called. I did this to “calibrate” the test… to make sure that the test could pass for the right reasons, even if the implementation was not yet correct. I’m not sure I buy this anymore, really. Do I really need to know that “Assert.AreEqual(60, myOutputVariable);” will work because I hard coded a value of 60 into the method being called? I really don’t think so.

The simplest thing that could possibly work is a misnomer. Hard coding a value is the simplest thing, but it’s worthless. Setting up the very basics of structure and process, without regard for any not-yet-coded functionality is a much more appropriate way to look at the simplest thing. You need to account for the actual requirements of what you are implementing, the core of the architecture that your team has standardized on, and any other bits and pieces of standards that make sense and should be in place for the system in question.

Did you get your test to pass? Good. Did it pass because you wrote production worthy code, without writing more than would make the test pass? Great!

laravel red green refactor

Refactor: For The Right Reasons

STOP! Hold on a second… before you go any further and before you even think about refactoring what you just wrote to make your test pass, you need to understand something: if your done with your requirements after making the test green, you are not required to refactor the code. I know… I’m speaking heresy, here. Toss me to the wolves, I’ve gone over to the dark side! Seriously, though… if your test is passing for the right reasons, and you do not need to write any test or any more code for you class at this point, what value does refactoring add?

Just because you wrote some code to make a test pass, doesn’t mean you need to refactor it. There is no rule or law that says you must refactor your code after making it green. There is a principle that says you should leave the campsite cleaner than when you got there. Sometimes the process of adding code and functionality leaves it clean to begin with and you just don’t need to do any additional work to clean it up.

If you write your first chunk of code to make a test pass and it’s simple, elegant and easy to understand and modify, then stop. You’re done. You don’t need to refactor. If you are adding the 25th chunk of code based on the 25th test and the code remains simple, elegant and easy to understand and modify, then stop! You don’t need to refactor. If, however, you write some code that is a duplication or is using some nested if-thens and loops, or is using hard coded values, or for whatever other reason it does not conform to all of the principles and guidelines that you follow in order to make your code simple, elegant, easy to understand and modify… ok, then you need to refactor.

So why should you follow the refactor portion of red/green/refactor? When you have added code that makes the system less readable, less understandable, less expressive of the domain or concern’s intentions, less architecturally sound, less DRY, etc, then you should refactor it.


Thanks

Thursday, August 20, 2015

What are the Pros and Cons of Laravel ?

Laravel (Pros and Cons): 

Some time ago Laravel 5 released and its consider that Laravel is the best PHP Framework. I am also using this framework. There are alot of pros and cons in laravel as in every framework. These are the following.

Laravel Pros and Cons
Pros:

- In Laravel we are using Composer for install the third party. This is same like  Ruby's gem bundle.  This is a easy way to get all updated code in package with just run a command

composer update

-Eloquent ORM is a simple, super fast ORM that makes working with database relations easy



-Very configurable and extendable. I can set up apps with the folder structure the way I like it and how it works best for me.

-Blade template engine. Very fast (compiles to PHP then caches the results) and very extendable. So easy to add new features without hacking the core.

-Artisan (CLI). Before I started using Laravel I had zero use for CLI tools like migrations and tasks. It’s so easy to create both of those things with Artisan that I can’t believe I waited so long to try it out!

-It also including reverse routing.

-Its documentation is also very beautiful.

Laravel Pros and Cons


Cons:

-Laravel is a new framework. So, for finding answers are still limited in comparison to CakePHP and CodeIgniter. However, the forums and IRC seem to be quite active with helpful people, so usually the answer is findable.



-Laravel’s core files are all within (at least) the Laravel namespace and not all of the files in core use a namespace slash ( a \ ) in front of a call to another core file, which makes extending some classes a bit trickier. This is not a huge issue and one not every developer will need to worry about.


Thanks

Tuesday, August 18, 2015

How to get value of protected object without getter/setter in php

Get value of protected object in php without getter/setter:

If there are any protected object and we want to get its value without creating any get() and set() method & without overriding, then use this method.

for e.g.
 I have a protected array:


Stripe\Coupon Object
(
    [_opts:protected] => Stripe\Util\RequestOptions Object
        (
            [headers] => Array
                (
                )
            [apiKey] => sk_test_Ghjgah2wFtSWkmvJXLge5siVGrM
        )
    [_values:protected] => Array
        (
            [id] => INSTA100
            [created] => 1439875363
            [percent_off] =>
            [amount_off] => 100
            [currency] => usd
            [object] => coupon
            [livemode] =>
            [duration] => once
            [redeem_by] =>
            [max_redemptions] =>
            [times_redeemed] => 0
            [duration_in_months] =>
            [valid] => 1
            [metadata] => Stripe\AttachedObject Object
                (
                    [_opts:protected] => Stripe\Util\RequestOptions Object
                        (
                            [headers] => Array
                                (
                                )
                            [apiKey] => sk_test_Gah2wFtSWkmvJXLge5siVGrM
                        )
                    [_values:protected] => Array
                        (
                        )
                    [_unsavedValues:protected] => Stripe\Util\Set Object
                        (
                            [_elts:Stripe\Util\Set:private] => Array
                                (
                                )
                        )
                    [_transientValues:protected] => Stripe\Util\Set Object
                        (
                            [_elts:Stripe\Util\Set:private] => Array
                                (
                                )
                        )
                    [_retrieveOptions:protected] => Array
                        (
                        )
                )
        )
)





Now i want to get all values of _values


For this i will use ReflectionClass which is a php class
               
$reflector = new \ReflectionClass($cpn);
                $classProperty = $reflector->getProperty('_values');
                $classProperty->setAccessible(true);
                $data = $classProperty->getValue($cpn);


Here $cpn is my object

Now print $data and you will get your required array.

Thanks