Friday, July 15, 2016

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

Wednesday, December 21, 2011

PHP on IIS

IIS Installation
Go to Start -> Control Panel -> Add Remove Program -> Add and Remove components -> Enable IIS -> Restart Machine
 
PHP INSTALLATION
1) Download PHP from "http://www.php.net/downloads.php" 2) Create a folder named php on c drive 3) Extract all of the files from the downloaded zip file into C:\PHP 5) Add the PHP directory path to the environment variables PATH
 
How to add environment variable PATH 1) Right-Click on My computer and choose "properties". 2) select the Advanced tab 3) click the "Environment Variables" button (There are two sections in the Environment Variables    window, User Variable and System Variables. We will be using System Variables. Scroll down until you find the variable PATH. Highlight and click on edit button,add the php path to the end of the line (C:\PHP)
 4) restart the machine. 
 
php.ini configuration
Rename php.ini-recommended file to php.ini in C:\PHP folder
 
Php.ini changes 
1) doc_root = C:\inetpub\wwwroot
2) cgi.force_redirect = 0
 
IIS_PHP Integration  
1) Open IIS ( start-controlpanel-performance and maintenance-administrative tools
2) Right click on Default website 
3) select properties 
4) Click on configuration 
5) Click Add 
6) Set "executable" to C:\PHP\php5isapi.dll 
7) Set "extension" to .php 
8) Click Apply, then OK 
9) Under ISAPI Filters ;Click "Add" 
10) Set Filter Name to PHP 
11) Set Executable to C:\PHP\php5isapi.dll 
12) Restart the Web Server ( right click on local computer select all tasks the click on IIS restart)
 
Testing 
1) Go to C:\inetpub\wwwroot 
2) create a file and type <?php echo phpinfo(); ?> ( the extension should be .php
3) Open your web browser and type: http://localhost/phpnfo.php
 
For the database connectivty you have to copy the ntwdblib.dll file on the system32 folder.