Post Top Ad

Monday, January 29, 2018

January 29, 2018

Laravel 5.6 will Support the Argon2i Password Hashing Algorithm


Image result for laravel 5.6  new features

In 2013, cryptographers and security practitioners around the world came together to create an open Password Hashing Competition (PHC) with the goal of selecting one or more password hash functions to be recognized as a recommended standard.
On July 20th, 2015 Argon2 that was designed by Alex Biryukov, Daniel Dinu, and Dmitry Khovratovich from the University of Luxembourg was selected as the final PHC winner. Argon2 comes in the following three versions:
  • Argon2d maximizes resistance to GPU cracking attacks.
  • Argon2i is optimized to resist side-channel attacks. It accesses the memory array in a password independent order.
  • Argon2id is a hybrid version. It follows the Argon2i approach for the first pass over memory and the Argon2d approach for subsequent passes.
x
With the release of PHP 7.2 in November of 2017, PHP now includes functions for both the 2d and i version. However, the 2d is not suitable for password hashing.
Laravel 5.6 that is due out next month will now feature Argon2i password hashing support thanks to Michael Lundbøl, and you can find out how it’s implemented through the following pull request.
The old style of bcrypt will continue to be supported and will remain the default, but if you are starting a new project then it might be worth considering using the Argon2i driver once Laravel 5.6 officially makes it release.

Sunday, January 14, 2018

January 14, 2018

Laravel Model Caching



Laravel Model Caching


You’ve probably cached some model data in the controller before, but I am going to show you a Laravel model caching technique that’s a little more granular using Active Record models. This is a technique I originally learned about on RailsCasts.
Using a unique cache key on the model, you can cache properties and associations on your models that are automatically updated (and the cache invalidated) when the model (or associated model) is updated. A side benefit is that accessing the cached data is more portable than caching data in the controller, because it’s on the model instead of within a single controller method.
Here’s the gist of the technique:
Let’s say you have an Article model that has many Comment models. Given the following Laravel blade template, you might retrieve the comment count like so on your /article/:id route:
<h3>$article->comments->count() {{ str_plural('Comment', $article->comments->count())</h3>
You could cache the comment count in the controller, but the controller can get pretty ugly when you have multiple one-off queries and data you need to cache. Using the controller, accessing the cached data isn’t very portable either.
We can build a template that will only hit the database when the article is updated, and any code that has access to the model can grab the cached value:
<h3>$article->cached_comments_count {{ str_plural('Comment', $article->cached_comments_count)</h3>
Using a model accessor, we will cache the comment count based on the last time the article was updated.
So how do we update the article’s updated_at column when a new comment is added or removed?
Enter the touch method.

Touching Models

Using the model’s touch() method, we can update an article’s updated_at column:
$ php artisan tinker

>>> $article = \App\Article::first();
=> App\Article {#746
     id: 1,
     title: "Hello World",
     body: "The Body",
     created_at: "2018-01-11 05:16:51",
     updated_at: "2018-01-11 05:51:07",
   }
>>> $article->updated_at->timestamp
=> 1515649867
>>> $article->touch();
=> true
>>> $article->updated_at->timestamp
=> 1515650910
We can use the updated timestamp to invalidate a cache, but how can we touch the article’s updated_at field when we add or remove a comment?
It just so happens that Eloquent models have a property called $touches. Here’s what our comment model might look like:
<?php

namespace App;

use App\Article;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $guarded = [];

    protected $touches = ['article'];

    public function article()
    {
        return $this->belongsTo(Article::class);
    }
}
The $touches property is an array containing the association that will get “touched” when a comment is created, saved, or removed.

The Cached Attribute

Let’s go back to the $article->cached_comments_count accessor. The implementation might look like this on the App\Article model:
public function getCachedCommentsCountAttribute()
{
    return Cache::remember($this->cacheKey() . ':comments_count', 15, function () {
        return $this->comments->count();
    });
}
We are caching the model for fifteen minutes using a unique cacheKey() method and simply returning the comment count inside the closure.
Note that we could also use the Cache::rememberForever() method and rely on our caching mechanism’s garbage collection to remove stale keys. I’ve set a timer so that the cache will be hit most of the time, with a fresh cache every fifteen minutes.
The cacheKey() method needs to make the model unique, and invalidate the cache when the model is updated. Here’s my cacheKey implementation:
public function cacheKey()
{
    return sprintf(
        "%s/%s-%s",
        $this->getTable(),
        $this->getKey(),
        $this->updated_at->timestamp
    );
}
The example output for the model’s cacheKey() method might return the following string representation:
articles/1-1515650910
The key is the name of the table, the model id, and the current updated_attimestamp. Once we touch the model, the timestamp will be updated, and our model cache will be invalidated appropriately.
Here’s the Article model if full:
<?php

namespace App;

use App\Comment;
use Illuminate\Support\Facades\Cache;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    public function cacheKey()
    {
        return sprintf(
            "%s/%s-%s",
            $this->getTable(),
            $this->getKey(),
            $this->updated_at->timestamp
        );
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function getCachedCommentsCountAttribute()
    {
        return Cache::remember($this->cacheKey() . ':comments_count', 15, function () {
            return $this->comments->count();
        });
    }
}
And the associated Comment model:
<?php

namespace App;

use App\Article;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $guarded = [];

    protected $touches = ['article'];

    public function article()
    {
        return $this->belongsTo(Article::class);
    }
}

What’s Next?

I’ve shown you how to cache a simple comment count, but what about caching all the comments?
public function getCachedCommentsAttribute()
{
    return Cache::remember($this->cacheKey() . ':comments', 15, function () {
        return $this->comments;
    });
}
You might also choose to convert the comments to an array instead of serializing the models to only allow simple array access to the data on the frontend:
public function getCachedCommentsAttribute()
{
    return Cache::remember($this->cacheKey() . ':comments', 15, function () {
        return $this->comments->toArray();
    });
}
Lastly, I defined the cacheKey() method on the Article model, but you would want to define this method via a trait called something like ProvidesModelCacheKey that you can use on multiple models or define the method on a base model that all our models extend. You might even want to use a contract (interface) for models that implement a cacheKey() method.
I hope you’ve found this simple technique useful!

Tuesday, January 9, 2018

January 09, 2018

Advanced Object-Oriented Programming in PHP




Object-oriented programming (OOP) is an important technique regardless of the programming language developers use, and PHP is no exception. This article will discuss how to develop advanced object-oriented programs in PHP.
Image result for php oop advanced

Introduction

PHP is a server-side scripting language used to develop web pages. In the recent times, PHP has become popular because of its simplicity. PHP code can be combined with HTML code and once the PHP code is executed, the web server sends the resulting content in the form of HTML or images that can be interpreted by the browser. We all know the power and importance of object-oriented programming or OOP. This is a technique that is widely used in the modern programming languages.

Common OOP Concepts Used in PHP

Inheritance – Inheritance is the most important concept of Object-oriented programming used in the most common programming language. Inheritance is based on the principle of parent and child classes. In PHP we achieve inheritance by extending the class. By extending a class, the child class inherits the properties of the parent class and additionally, we can add a few more properties.

Listing 1 – Sample code to show inheritance
class Employee {
 public $firstName = "";
 public $lastName = "";
 public $eCode = "";
 public $dept = "";
 
 public function dailyCommonTask() {
  // Code for routine job
 }
}

class Accountant extends Employee {
 public function processMonthlySalary($eCode) {
  // Code for processing salary
 }
}

In the code snippet above we see that the class Accountant is extending the Employee class. An accountant is an employee first, so he performs the daily common jobs as other employees do. At the same time, it is the Accountant's job to process the salary of other employees.

Public, Private and Protected – As in any object-oriented language, PHP also includes the concept of Public, Private and Protected access modifiers.

      • Public – With having public access the code is visible and can be modified by any code from anywhere.
      • Private – With having private access the code is visible and can be modified from within the class only.
      • Protected – With having protected access the code is visible and can be modified from the same class or any of its child class.

Overloading – The overloading feature enables us to have two methods with the same name but with different parameters. Shown in the following code snippet:

Listing 2 – Sample code to show overloading
class Accountant extends Employee {
 public function processMonthlySalary($eCode) {
  // Code for processing salary
 }
 public function processMonthlySalary($eCode, $variablePayFlag, $variablePercentage) {
  if($variablePayFlag) {
     echo "Please process the salary with variable pay ";
  } else {
     echo " Please process the salary without variable pay ";
  }
 }
}

In the code above, we have two methods with the same name ('processMonthlySalary'). In an organization, not all the employees will have the variable pay component in their salary. Hence the accountant will have to process the salary using two different approaches:

      • With variable pay
      • Without variable pay

While processing the salary with variable pay, the accountant needs to mention the amount of the variable pay component.

Note of clarification added to original article post date:
In the above example, we explained the general concept of method overloading. But during actual implementation, we need a PHP function called func_get_args () to handle multiple method signature (having same method name) with different arguments. The func_get_args ()is used inside a PHP function which holds all the arguments (as an array) passed into it. So the same function can be called with different arguments.

For example, let us take a function called myTestFunction () and we want to use it as an overloaded function.

function myTestFunction() 
{
    print_r(func_get_args());
}

Now, multiple calls to this function could be as shown below. The func_get_args ()will have all the arguments which can be used as per requirement. The first call does not pass any argument, the second call passes one argument and the third one sends two arguments. So the function is acting as an overloaded function.

myTestFunction ();
myTestFunction ("Hello");
myTestFunction ("Hello","Dear"); 

There is also another way of implementing overloading in PHP — by using __call() and __callStatic() methods.

For example, the code snippet below shows the arguments passed into it along with the method name. Here $name is case sensitive. The output will print the method name and the arguments passed into it.

public function __call($name, $arguments)
    {

        echo "We are calling in object context '$name' "
             . implode(', ', $arguments). "\n";
    }

public static function __callStatic($name, $arguments)
    {

        echo "We are calling in static context '$name' "
             . implode(', ', $arguments). "\n";
    } 

Accessors and Mutators – Commonly known as getters and setters, or Accessors and Mutators, are widely used in every programming language. Accessors (or getters) are functions that are used to return or get the value of the class level variables. Mutators (or setters) are functions that are used to set or modify the value of a class level variable. These types of classes are used to transfer the data in a collective way from one layer to another. Let us consider the following example:

Listing 3 – Sample code for Accessors and Mutators
class Employee {
 public $firstName =  "";
 public $lastName = "";
 public $eCode =  "";
 public $dept = "";
  public function getfirstName() {
  return $this->firstName();
 }
 public function setfirstName($firstName) {
  $this->firstName = $firstName;
 }
 public function getlastName() {
  return $this->lastName();
 }
 public function setlastName($lastName) {
  $this->lastName = $lastName;
 }
 public function getECode() {
  return $this->eCode();
 }
 public function setECode($eCode) {
  $this->eCode = $eCode;
 }
 public function getDept() {
  return $this->dept();
 }
 public function setDept($dept) {
  $this->dept = $dept;
 }
}

These types of classes are very helpful when we have to transfer the entire Employee object from one layer to another.

Static – Using a static keyword for both variable and method is a common practice in object-oriented programming. Static means that the variable or the method is available per instance of the class. Static methods or variables are used without creating an instance of the class. In fact, the static variables are not accessible via the instance of the class. While creating static methods you must take care that the $this variable is not allowed within a static method.

Listing 4 – Sample code for static keyword and method
class StaticSample {
    public static $my_static = 'Sample Static variable';
    public function staticValue() {
        return self::$my_static;
    }
 public static function aStaticMethod() {
        echo "This is the Hello message from static method";
    }
}

class StaticShow extends StaticSample {
    public function checkStatic() {
        return parent::$my_static;
    }

 public function checkStaticMethod() {
        return parent::$aStaticMethod;
    }
}

Abstract Class – In PHP, these two features of object-oriented programming are used very frequently. Abstract classes that can't be instantiated rather they can be inherited. The class that inherits an abstract class can also be another abstract class. In PHP we can create an abstract class by using the keyword – 'abstract'.

Listing 5 – Sample code for Abstract Class
abstract class testParentAbstract {
 public function myWrittenFunction() {
  // body of your funciton
 }
}

class testChildAbstract extends testParentAbstract {
 public function myWrittenFunctioninChild() {
  // body of your function
 }
}

In the above example, we can create an instance of the child class – testChildAbstract, but we can't create the instance of the parent class – testParentAbstract. As we see that the child class is extending the parent class, we can use the property of the parent class in the child class. We can also implement an abstract method in our child class as per our need.

Interface – In object-oriented programming, the interface is a collection of definitions of some set of methods in a class. By implementing an interface, we force the class to follow the methods defined in the interface. In PHP, interface is defined as in any other language. First, we need to define the interface using the keyword – 'interface'. When implementing, we just need to mention the 'implements' keyword in the implementing class.

Listing 6 – Sample Code for Interface
interface myIface {
 public function myFunction($name);
}

class myImpl implements myIface {
 public function myFunction($name) {
  // function body
 }
}

Summary

PHP has emerged as one of the most popular languages for web application development. It has been enhanced to support different aspects of programming and of those, the object-oriented features are the most important to understand and implement.