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

Sunday, August 16, 2015

How to create real time chat using with Node.js, Socket.io and ExpressJS

Real time chat using Node.js, Socket.io, ExpressJS:

For creating a real time chat you have to do some following steps:

Setup Environment
Of course, the first thing to do is get NodeJS installed on your system.Once you have NodeJS installed, you're ready to setup the needed instruments.

ExpressJS - this will manage the server and the response to the user
Jade - template engine
Socket.io - allows for real time communication between the front-end and back-end

Continuing on, within an empty directory, create a package.json file with the following content.



{
    "name": "RealTimeWebChat",
    "version": "0.0.0",
    "description": "Real time web chat",
    "dependencies": {
        "socket.io": "latest",
        "express": "latest",
        "jade": "latest"
    },
    "author": "developer"
}


By using the Terminal (under Windows - command prompt), navigate to your folder and execute:

npm install

Within a few seconds, you'll have all the necessary dependencies downloaded to the node_modules directory

Developing the Backend
Let's begin with a simple server, which will deliver the application's HTML page, and then continue with the more interesting bits: the real time communication. Create an index.js file with the following core expressjs code:

var express = require("express");
var app = express();
var port = 3700;

app.get("/", function(req, res){

    res.send("It works!");
});

app.listen(port);
console.log("Listening on port " + port);

Above, we've created an application and defined its port. Next, we registered a route, which, in this case, is a simple GET request without any parameters. For now, the route's handler simply sends some text to the client. Finally, of course, at the bottom, we run the server. To initialize the application, from the console, execute:

node index.js

The server is running, so you should be able to open http://127.0.0.1:3700/ and see:

It works!

Now, instead of "It works" we should serve HTML. Instead of pure HTML, it can be beneficial to use a template engine. Jade is an excellent choice, which has good integration with ExpressJS. This is what I typically use in my own projects. Create a directory, called tpl, and put the following page.jade file within it:

<!DOCTYPE html>
html
    head
        title= "Real time web chat"
    body
        #content(style='width: 500px; height: 300px; margin: 0 0 20px 0; border: solid 1px #999; overflow-y: scroll;')
        .controls
            input.field(style='width:350px;')
            input.send(type='button', value='send')


The Jade's syntax is not so complex, but, for a full guide, I suggest that you refer to jade-lang.com. In order to use Jade with ExpressJS, we require the following settings.

app.set('views', __dirname + '/tpl');
app.set('view engine', "jade");
app.engine('jade', require('jade').__express);
app.get("/", function(req, res){
    res.render("page");
});


This code informs Express where your template files are, and which template engine to use. It all specifies the function that will process the template's code. Once everything is setup, we can use the .render method of the response object, and simply send our Jade code to the user.

The output isn't special at this point; nothing more than a div element (the one with id content), which will be used as a holder for the chat messages and two controls (input field and button), which we will use to send the message.

Because we will use an external JavaScript file that will hold the front-end logic, we need to inform ExpressJS where to look for such resources. Create an empty directory, public, and add the following line before the call to the .listen method.

app.use(express.static(__dirname + '/public'));

So far so good; we have a server that successfully responds to GET requests. Now, it's time to add Socket.io integration. Change this line:

app.listen(port);

to:

var io = require('socket.io').listen(app.listen(port));


Above, we passed the ExpressJS server to Socket.io. In effect, our real time communication will still happen on the same port.

Moving forward, we need to write the code that will receive a message from the client, and send it to all the others. Every Socket.io application begins with a connection handler. We should have one:

io.sockets.on('connection', function (socket) {
    socket.emit('message', { message: 'welcome to the chat' });
    socket.on('send', function (data) {
        io.sockets.emit('message', data);
    });
});


The object, socket, which is passed to your handler, is actually the socket of the client. Think about it as a junction between your server and the user's browser. Upon a successful connection, we send a welcome type of message, and, of course, bind another handler that will be used as a receiver. As a result, the client should emit a message with the name, send, which we will catch. Following that, we simply forward the data sent by the user to all other sockets with io.sockets.emit.

With the code above, our back-end is ready to receive and send messages to the clients. Let's add some front-end code.
Developing the Front-end

Create chat.js, and place it within the public directory of your application. Paste the following code:

window.onload = function() {

    var messages = [];
    var socket = io.connect('http://localhost:3700');
    var field = document.getElementById("field");
    var sendButton = document.getElementById("send");
    var content = document.getElementById("content");

    socket.on('message', function (data) {
        if(data.message) {
            messages.push(data.message);
            var html = '';
            for(var i=0; i<messages.length; i++) {
                html += messages[i] + '<br />';
            }
            content.innerHTML = html;
        } else {
            console.log("There is a problem:", data);
        }
    });

    sendButton.onclick = function() {
        var text = field.value;
        socket.emit('send', { message: text });
    };

}


Our logic is wrapped in a .onload handler just to ensure that all the markup and external JavaScript is fully loaded. In the next few lines, we create an array, which will store all the messages, a socket object, and few shortcuts to our DOM elements. Again, similar to the back-end, we bind a function, which will react to the socket's activity. In our case, this is an event, named message. When such an event occurs, we expect to receive an object, data, with the property, message. Add that message to our storage and update the content div. We've also included the logic for sending the message. It's quite simple, simply emitting a message with the name, send.

If you open http://localhost:3700, you will encounter some errors popup. That's because we need to update page.jade to contain the necessary JavaScript files.

head
    title= "Real time web chat"
    script(src='/chat.js')
    script(src='/socket.io/socket.io.js')

Notice that Socket.io manages the delivery of socket.io.js. You don't have to worry about manually downloading this file.

We can again run our server with node index.js in the console and open http://localhost:3700. You should see the welcome message. Of course, if you send something, it should be shown in the content's div. If you want to be sure that it works, open a new tab (or, better, a new browser) and load the application. The great thing about Socket.io is that it works even if you stop the NodeJS server. The front-end will continue to work. Once the server is booted up again, your chat will be fine too.

Thursday, August 13, 2015

Short and easy way to write a route path in Laravel 5.1

Short & Easy way to define route in Laravel:

In Laravel 4.2, Genrallay we define any route like this:



Route::post('/sign-in', 'UserController@signIn');
                              
                           OR

Route::get('/sign-in', 'UserController@signIn');

In Laravel 5.1 we can write route like this & also can write a different method.


We don't need to write 'Route::' for define any route. We can simply write it down as

post('/sign-in', 'UserController@signIn');
                              
                           OR

get('/sign-in', 'UserController@signIn');

 Thanks

Add extra field in migration after creating table in Laravel 5.1

Add extra field in migration after creating table:

First time we create a table's migration & execute migration command. After this , we realize that we have to add a new field in database.

For this, we can modify table by this easy way.

Firstly run this command for create a new migration file.

php artisan make:migration add_email_in_users_details_table

It will create a new file in migration file. Write in its up() function the following lines.



        Schema::create('user_details', function ($table) {
            $table->string('email');
          });


and in down() function write the following lines:



Schema::create('user_details', function ($table) {
            $table->drop_column('email');
          });


Make sure you put the same table name which you want to edit.

Now run migration command for this file.

Thanks

Wednesday, August 12, 2015

How to send email using Node.js?

 Send email using Node.js:

In this blog i am going to discuss about sending e-mail with Node.js, Express.js and NodeMailer package. In many forums and blogs people used to ask about sending e-mail’s using Node.js for account verification, password recovery and promotion. So let’s begin with tutorial and at the end you will have Node application which is able to send e-mail’s to any one’s account.



Create package.json file and keep it in any folder. Put the below code in it.

package.json

{
"name": "email-node",
"version": "1.0.0",
"dependencies": {
"nodemailer": "~0.7.1",
"express": "~4.5.1"
}
}




Once done. Switch to that folder using Command prompt or Terminal and type npm install. It will download and install the dependencies our project need.

npm install

After completion you will able to see node_modules folder in your project directory.

Implementing Server.js:



Let’s begin with creation of our Server file. Paste code shown below in file named as “Server.js”.

Server.js

var express=require('express');
var nodemailer = require("nodemailer");
var app=express();
app.listen(3000,function(){
console.log("Express Started on Port 3000");
});




This is basic block of our app. If you run it in Terminal you will see console message. Now let’s add some routing logic to tell our app what is supposed to do when Request comes from browser. Add these code just above the app.listen line.

app.get('/',function(req,res){
res.sendFile('index.html');
});


Now when you try to open your app from browser, it will return the index.html as response. Let me show you basic snippet of HTML code.

index.html

<div id="container">
<div></div>
Node.JS Email application
<div>
<h1>Mailer In Node.JS</h1>
<input id="to" type="text" placeholder="Enter E-mail ID where you want to send" />
<input id="subject" type="text" placeholder="Write Subject" />
<textarea id="content" cols="40" rows="5" placeholder="Write what you want to send"></textarea>
<button id="send_email">Send Email</button>
<span id="message"></span>
</div>


Now next thing to do is to call our Server from HTML page when user hit on ‘Send Email’ Button. To do so at client end i am using jQuery. Here is code snippet of jQuery inside HTML page only.

index.html

<script>
$(document).ready(function(){
    var from,to,subject,text;
    $("#send_email").click(function(){    
        to=$("#to").val();
        subject=$("#subject").val();
        text=$("#content").val();
        $("#message").text("Sending E-mail...Please wait");
        $.get("http://localhost:3000/send",{to:to,subject:subject,text:text},function(data){
        if(data=="sent")
        {
            $("#message").empty().html("Email is been sent at "+to+" . Please check inbox !");
        }

});
    });
});
</script>



Notice : At $.get we are calling our app with ‘/send’ as handler so now we have to add router in our Server.js file in order to deal with this request. So let’s add some code to handle this route request. Add these code just below of app.get(‘/’) line. File name : Server.js

Server.js

app.get('/send',function(req,res){
//code to send e-mail.
//Will be shown soon.
});


Adding NodeMailer code:

Okay we are almost there, now we have to handle the Mail system. First of all we have to Define Mail transport System (SMTP) so that from that E-mail box our e-mail will be sent. For ease, you can add your Gmail account and password. Add this code just in Server.js just below the ‘var app=express()’ line.

var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "yourID@gmail.com",
pass: "Your Gmail Password"
}
});


We will use this Object to send e-mail. Our app design is when user click on ‘Send email’ Button then only e-mail should be sent, and we have did that part in “app.get(‘/send’)” router. So in that block only paste the code shown below.

var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});




In above code we have read GET variables send from HTML page and we have call “sendMail()” function using Transport object we have created above. In case there is any confusion here is a complete Server.js file.

Server.js

var express=require('express');
var nodemailer = require("nodemailer");
var app=express();
/*
Here we are configuring our SMTP Server details.
STMP is mail server which is responsible for sending and recieving email.
*/
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "yourID@gmail.com",
pass: "Your G-mail password"
}
});

/*------------------SMTP Over-----------------------------*/

/*------------------Routing Started ------------------------*/

app.get('/',function(req,res){
res.sendFile('index.html');
});
app.get('/send',function(req,res){
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
});



/*--------------------Routing Over----------------------------*/

app.listen(3000,function(){
console.log("Express Started on Port 3000");
});


And this is how HTML page looks like with all styles and JS.

index.html

<html>
<head>
<title>Node.JS Email application</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script>// <![CDATA[
$(document).ready(function(){
    var from,to,subject,text;
    $("#send_email").click(function(){    
        to=$("#to").val();
        subject=$("#subject").val();
        text=$("#content").val();
        $("#message").text("Sending E-mail...Please wait");
        $.get("http://localhost:3000/send",{to:to,subject:subject,text:text},function(data){
        if(data=="sent")
        {
            $("#message").empty().html("

Email is been sent at "+to+" . Please check inbox !

");
        }

});
    });
});
</script>
</head>
<body>
<div id="container">
<h1>Mailer In Node.JS</h1>
<input id="to" type="text" placeholder="Enter E-mail ID where you want to send" />
<input id="subject" type="text" placeholder="Write Subject" />
<textarea id="content" cols="40" rows="5" placeholder="Write what you want to send"></textarea>
<button id="send_email">Send Email</button>
<span id="message"></span>
</div>
</div>
</body>
</html>

Secure site with Password Protection

Secure Site using password:

Step1:- At first open your apache configuration file and add the line AllowOverride All to it.



<Directory /home/abhimanyu/workspace/test/>

    AllowOverride All

Step2:- Now open your .htaccess file and add the following line of code to it



AuthType Basic
AuthName "Restricted Files"
AuthUserFile /etc/apache2/securepass/.htpasswd
Require valid-user

For details of these lines go here.




Step3:- We need a package of apache as utils to get password utility
and can get it by the following command

sudo apt-get install apache2-utils



Step 4:-Now create securepass dir by running



sudo mkdir /etc/apache2/securepass/
                                              then
sudo htpasswd -c /etc/apache2/securepass/.htpasswd username
and add your password



Step 5:--Now restart your apache server by following command
  sudo service apache2 restart
and check at for your site(domain)  and its got password protected.