Wednesday, July 20, 2016

PHP - google analytics ecommerce tracking from server side

Create a new Analytics account

Open google.com/analytics, click the Sign in to Analytics button [top right (Google Analytics) ], and follow the instructions.

Enable eCommerce in your reports

Sign in to your Analytics account.
Navigate to the desired account, property and view.
In the VIEW column, select Ecommerce Settings.
Click the Enable Ecommerce toggle ON.
Optional: Click the Enable Related Products toggle ON.
Click Next step.
Click Submit.

Google analytics integration with PHP (server side)

Download the Server Side Google Analytics class from github. Click here to download.Extract the files in your project folder. In case of laravel, copy the files in the project public folder

 Usage - Ecommerce tracking

<?php

 include(public_path().'/ss-ga.class.php'); [public path - Laravel public directory ]

     

$ssg_1 = new ssga( '<Your GA tracking id>','<Site name>' );

//$transaction_id, $affiliation, $total, $tax, $shipping, $city, $region, $country
$ssg_1 ->send_transaction("11111111", "Insurance", 500, 12, 0,"", "", "");

$ssg_2 = new ssga( '<Your GA tracking id>','<Site name>' );
//$transaction_id, $sku, $product_name, $variation, $unit_price, $quantity
$ssg_2->send_item("11111111", "222222", "TEST-INSURANCE", "", 50, 4);

?>

Monday, July 18, 2016

Laravel UUID generation

We can use the following package to generate UUID from laravel. 

ramsey/uuid

You can download it from UUID . 

Installation

Run the following command from the command prompt

> composer require ramsey/uuid

Usage

<?php
    
   use Ramsey\Uuid\Uuid;
  
   class Uuid{
    
            public function generateUuid(){
                    $uuid4 = Uuid::uuid4();
return $uuid4->toString();
            }
   }
?>

Friday, July 15, 2016

Laravel - Swagger documentation

Swagger is a powerful tool to generate interactive documentation for your RESTful API using phpdoc annotations

Installation

  • Add the following dependency in the composer.json file
"require": {
        "zircote/swagger-php": "*",
}
  • Run the following command to install the package
composer update
  • Add annotations to your php file
PushController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Jobs\SendReminderEmail;
use App\Jobs\SendWelcomeEmail;
use App\Utilities\AuditTrail;


class PushController extends Controller
{

public function __construct(AuditTrail $AuditTrail){
$this->objAuditTrail = $AuditTrail;
}
/**
* @SWG\Info(title="Halo", version="1.0")
* @SWG\Get(
* path="/push",
* tags={"Queue"},
* @SWG\Response(response="200", description="Push job to the queue")
* )
*/
public function push(){

$customerName = 'Jefferey Turner';
$job = (new SendWelcomeEmail($customerName));

$this->dispatch($job);
$job->delete();

$customerName = 'Fay Padberg';
$job = (new SendReminderEmail($customerName));

$this->dispatch($job);
$job->delete();

$this->objAuditTrail->logData('Job push controller','Job pushed onto queue');
return 'Email pushed onto queue';

}
}

  • Generate the swagger documentation
    • From php 
$swagger = \Swagger\scan(<Project Path>);
header('Content-Type: application/json');
echo $swagger;
  • From the command line.Go to vendor/bin folder and issue the following command

    swagger <Project directory> --output <Output directory>
Eg: swagger ..\..\\app --output ..\..\public\api\
Swagger will create the json file (swagger.json) and store it in public/api folder. 
swagger.json
{
"swagger": "2.0",
"info": {

"title": "Halo",
"version": "1.0"

},
"paths": {

"/push": {
"get": {
"tags": [
"Queue"
],
"responses": {

"200": {
"description": "Push job to the queue"
}
}
}
}
},
"definitions": {}

}

View the API resources withe the help of swagger UI

Swagger UI is a dependency-free collection of HTML, Javascript, and CSS assets that dynamically generate documentation from a Swagger.json file.You can use the swagger-ui code AS-IS.This documentation we are describing the integration with Laravel 5.2
  • Download the Swagger UI from https://github.com/swagger-api/swagger-ui and extract the files.
  • Create the folder (swagger) folder in resources/view folder
  • Copy the files from dist folder and put it in swagger folder.
  • Copy the js,css,images and put it in public folder
  • Change the index.html file to index.blade.php
  • Make the following changes in index.blade.php.(Use blade template directives)

<link href="{{asset('css/typography.css')}}" media='screen' rel='stylesheet' type='text/css'/>
<link href="{{asset('css/reset.css')}}" media='screen' rel='stylesheet' type='text/css'/>
<link href="{{asset('css/screen.css')}}" media='screen' rel='stylesheet' type='text/css'/>
<link href="{{asset('css/reset.css')}}" media='print' rel='stylesheet' type='text/css'/>
<link href="{{asset('css/print.css')}}" media='print' rel='stylesheet' type='text/css'/>
<script src="{{asset('lib/jquery-1.8.0.min.js')}}" type='text/javascript'></script>

<script src="{{asset('lib/jquery.slideto.min.js')}}" type='text/javascript'></script>
<script src="{{asset('lib/jquery.wiggle.min.js')}}" type='text/javascript'></script>
<script src="{{asset('lib/jquery.ba-bbq.min.js')}}" type='text/javascript'></script>
<script src="{{asset('lib/handlebars-2.0.0.js')}}" type='text/javascript'></script>
<script src="{{asset('lib/js-yaml.min.js')}}" type='text/javascript'></script>
<script src="{{asset('lib/lodash.min.js')}}" type='text/javascript'></script>
<script src="{{asset('lib/backbone-min.js')}}" type='text/javascript'></script>

<script src="{{asset('js/swagger-ui.js')}}" type='text/javascript'></script>
<script src="{{asset('lib/highlight.7.3.pack.js')}}" type='text/javascript'></script>
<script src="{{asset('lib/jsoneditor.min.js')}}" type='text/javascript'></script>
<script src="{{asset('lib/marked.js')}}" type='text/javascript'></script>
<script src="{{asset('lib/swagger-oauth.js')}}" type='text/javascript'></script>
  • Change the url link in the index.blade.php
  • Create the controller to handle the request.
SwaggerController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class SwaggerController extends Controller
{

public function index(){
return view('swagger.index');
}
}
  • Update the routes.php
Route::get('swagger', 'SwaggerController@index');
  • Link to view the API documentation
http://<server>/swagger [http://api.int.halo.devthing.link/swagger]

Laravel - AWS SQS Queuing

There are many different drivers for Laravel for the queuing service, the default is "sync". We can use queues on external service like Amazon SQS.Documentation is based on the SQS messaging service.
  • Add the following dependency in the composer.json file
"require": {
        "aws/aws-sdk-php": "^3.14"
}
  • Run the following command to install the package
composer update
  • Configuration for the queue.
Configuration file is stored in config/queue.php. Make the following changes.
  • Configure the connection parameters for SQS

'sqs' => [
'driver' => 'sqs',
'key' => <Access Key ID>,
'secret' => <Secret Access Key>,
'prefix' => 'https://<Region>.amazonaws.com/<Your Account Id>',[eg:https://sqs.eu-west-1.amazonaws.com/11111111111]
'queue' => <Queue Name>[eg:halo-renewals],
'region' => <region>[eg:eu-west-1],
],
  • Configure the default driver (.env file)
QUEUE_DRIVER=sqs
  • Creating Job classes (We are creating two job classes to send email to the user.Welcome mail and the reminder mail). Issue the following commands from the terminal
 php artisan make:job SendWelcomeEmail
php artisan make:job SendReminderEmail
          Jobs will be stored in the app/jobs directory
    • Make the following changes in your job files.
SendWelcomeEmail.php
<?php
namespace App\Jobs;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Mail\Mailer;

class SendWelcomeEmail extends Job implements ShouldQueue
{


use InteractsWithQueue, SerializesModels;

protected $emailAddress;

/**
* Create a new job instance.
*
* @return void
*/
public function __construct($emailAddress)
{

$this->emailAddress = $emailAddress;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(Mailer $mailer)
{

$mailer->send('emails.welcome', [], function($message) {
$message->from('<From email id>', 'Queue Test Mail');
$message->to($this->emailAddress)->subject('Welcome Email');

});
}
}

SendReminderEmail.php

<?php
namespace App\Jobs;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Mail\Mailer;

class SendReminderEmail extends Job implements ShouldQueue
{


use InteractsWithQueue, SerializesModels;

protected $emailAddress;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($emailAddress)
{

$this->emailAddress = $emailAddress;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(Mailer $mailer)
{

$mailer->send('emails.reminder', [], function($message) {
$message->from('<From email id>', 'Queue Test Mail');
$message->to($this->emailAddress)->subject('Reminder Email');

});
}
}
  • Create following template files for the email content in the resources/views/emails folder
  • welcome.blade.php
  • reminder.blade.php
  • Create the controller to push the jobs in the queue.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Jobs\SendReminderEmail;
use App\Jobs\SendWelcomeEmail;

class MyController extends Controller
{

public function Pushjobs(){
$hardCodedEmail = '<To Email Address>';
$job = (new SendWelcomeEmail($hardCodedEmail));

$this->dispatch($job);
$job->delete();

$hardCodedEmail = '<To Email Address>';
$job = (new SendReminderEmail($hardCodedEmail));

$this->dispatch($job);
$job->delete();

}
}
Pushjobs method will push two jobs into the AWS SQS.(Welcome email and Reminder email)
  • Run the jobs as they are pushed into the queue.Run the following command from the terminal.
php artisan queue:listen
Laravel will pull the jobs from the SQS and process it.

Laravel - Audit Trail -Configuring Custom Logging (File and DB logging)

Laravel comes with a built in error and exception handling functions to create the log files.Laravel is also integrated with the Monolog logging library,  which support variety of log handlers.Monolog sends logs to files,sockets,inboxes,databases and various web services.  

Configuring Custom Logging (File and DB logging)

  • Configure the Logging mode in the .env file.

AUDIT_TRAIL=DB [DB - Store the logs in the database, FILE -Store the logs in the file(/storage/logs/Audit_Trail_<YYY-MM-DD>)] 
  • Create the model class. Issue the following command on the terminal.
php artisan make:model model/log --migration
Laravel will create the log.class in the app/model folder and also create the migration file in the database/migrations folder
  •  Make the following changes in the migration file.

<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLogsTable extends Migration
{

/**
* Run the migrations.
*
* @return void
*/
public function up()
{

Schema::create('logs', function (Blueprint $table) {
$table->increments('id');
$table->string('userid',50);
$table->string('action',250);
$table->text('message');
$table->string('ipaddress',50);
$table->timestamps();
});

}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{

Schema::drop('logs');
}
}
  • Run the following command
php artisan migrate
  • Create DBHandler.php file to store the logs into the database and paste the following code (App/Utilities folder)

    <?php
    namespace App\Utilities;
    use Monolog\Logger;
    use Monolog\Handler\AbstractProcessingHandler;
    use App\model\log;

    class DBHandler extends AbstractProcessingHandler{
    public function __construct($level = Logger::DEBUG,$bubble = true){
    parent::__construct($level, $bubble);
    }


    protected function write(array $record){
    $objLog = new log();
    $objLog->userid = '1'; //to be changed
    $objLog->action = $record['context']['path'];
    $objLog->message = $record['formatted'];
    $objLog->ipaddress = $record['context']['ip'];
    $objLog->save();
    }

    }
  • Create AuditTrail.php file to handle the log request (App/Utilities folder)

<?php
namespace App\Utilities;
use Monolog\Logger;
use App\Utilities\PDOHandler;
use App\Utilities\DBHandler;
use Monolog\Handler\StreamHandler;
use Illuminate\Support\Facades\Request;

class AuditTrail{
public function logData($action,$message){
$ipAddress = Request::ip();
$browser = Request::header('User-Agent');
$path = Request::path();
$url = Request::fullUrl();

$message = (!empty($message))?$message:null;
$action = (!empty($action))?$action:null;
$log = new Logger('Audit Log');
if(!empty(env('AUDIT_TRAIL')) && env('AUDIT_TRAIL') == 'FILE'){
$fileName = 'Audit_Trail_'.date('Y-m-d');
$log->pushHandler(new StreamHandler(storage_path().'/logs/'.$fileName.'.log', Logger::DEBUG));
$log->addInfo($action,array('message'=>$message,'ip'=>$ipAddress,'browser'=>$browser,'path'=>$path,'url'=>$url));

}
else if(!empty(env('AUDIT_TRAIL')) && env('AUDIT_TRAIL') == 'DB'){

$log->pushHandler(new DBHandler());
$log->addInfo($action,array('message'=>$message,'ip'=>$ipAddress,'browser'=>$browser,'path'=>$path,'url'=>$url));

}
}
}

How to log the action

  • Create Controller class. Issue the following command

php artisan make:controller  MyController (Create MyController.php file in App/Http/Controllers folder)

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Utilities\AuditTrail;

class MyController extends Controller
{



public function __construct(AuditTrail $AuditTrail){

$this->objAuditTrail = $AuditTrail;
}


public function Profile(){

$this->objAuditTrail->logData(array('action'=>'My Controller : Profile Action','message'=>'Profile data inserted successfully'));
}
}

Laravel Migration and Seeding

Migration

Migrations are like version control of the database. Migrations are a series of time stamped instructions for making changes to your database. A migration file contains a class which have a series of SQL methods for adding tables, updating tables or dropping tables.
Migration file will have two methods
up method - Make changes to the database
down method - Roll back the changes
When a migration run, it is recorded in a 'migrations' table in the database.Laravel knows which migrations have already run and which all are pending.
First we need to create the migrations table in the database, run the following command from the terminal.

php artisan migrate:install

This will create a migrations table in your database.
Creating Migrations

php artisan make:migration create_accounts_table --create=accounts

create_accounts_table - migration name
Migration file will be placed in your database/migrations directory. Each migration file name contains a timestamp which allows laravel to determine the order of the migrations. (Eg: 2016_01_28_103708_create_accounts_table.php)
migration file will have the following
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAccountsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('accounts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('password', 60);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
        Schema::drop('accounts');
}
}
When the migration is run,the instructions in the up method are run. When the migration is rolled back, the instructions in the down methods are run

Run the migrate command from the terminal
php artisan migrate
Laravel will create a account table in the database

Seeding

Applications need some data loaded inorder to run successfully in development and test. Laravel introduced a simple method of seeding the database with test data using seed classes. Seed classes are stored in database/seeds directory. By default, a DatabaseSeeder class is defined for you.
Run the follwing command from your terminal to generate the seeder
php artisan make:seeder AccountsTableSeeder
It will create the AccountsTableSeeder.php file in the database/seeds directory
File will have the following
<?php
use Illuminate\Database\Seeder;
class AccountsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('accounts')->insert([
'name' => str_random(10),
'password' => bcrypt('secret'),
]);
}
}
Issue the following command on your terminal to run the seeding
php artisan db:seed --class=AccountsTableSeeder

Using modal factories

Instead of manually specifying the attributes for each model, you can use modal factories to generate large amount of records in the database.
  • Create the model class. Run the following command from your terminal
php artisan make:model account
   It will create the model class in the app directory
  • Define your model factory in the ModelFactory (database/factories/ModelFactories.php)

$factory->define(App\account::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'password' => bcrypt(str_random(10)),
];
});
  • Make the necessary changes in the AccountTableSeeder file
<?php
use Illuminate\Database\Seeder;
class AccountsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
factory(App\account::class, 50)->create()->each(function($u) {
$u->posts()->save(factory(App\Post::class)->make());
});
}
}
  • Run the following command
php artisan make:seeder AccountsTableSeeder
(Will create 50 records in the database)

Laravel Installation

Server Requirement

  • PHP Version
    • Minimum required PHP version for
      • Laravel 5.2/5.1 is PHP >= 5.5.9
      • Laravel 5.0 is PHP >= 5.4

Installation Steps

  • Laravel requires Composer to manage its dependencies.Download and install composer from Composer
  • Issue the following command on your terminal

        composer create-project --prefer-dist laravel/laravel Halo

        create-project - operation
        laravel/laravel- path to the framework for the project
        Halo - path to the project folder
        --prefer-dist - Current distribution
  • It will install the stable version of laravel and its dependencies. Current stable version for laravel is 5.2
  • If you want to install the different version of laravel, you can issue the following command on your terminal

               composer create-project laravel/laravel Halo "~5.0.0" --prefer-dist

Refer :  laravel.com