Sunday, July 26

What's New in PHP 7.


   For all the businessmen, who are using PHP, 2015 has been an important as after eleven years, its 5.0 release that is finally coming our way. The all new major version of PHP is all set for release before the end of the year. PHP 7 is bringing a lot of new language features and an amazing performance boost.

However do you know how this will impact on your current PHP codebase? How safe it is to update? And what are the points that changed? Let’s have a look at PHP 7 and find what’s to come with it:

Performance Enhancements –



Unquestionably, performance is one of the major points why you should upgrade your servers as soon as a stable version is released.

Phpang RFC has introduced the core refactoring, which makes PHP 7 as quick as HHVM. The official level is extremely impressive – a lot of actual world apps are running on PHP 5.6 will run at least twice as instant on PHP 7.

For thorough performance level, you can give a look at Rasmus Lerdorf’s presentation at PHP Australia. Below, you can find WordPress benchmarks from that presentation:

The best thing about PHP 7 is that it handles more than twice as a lot of requests per second that in realistic terms will show a 100% enhancement on performance for WordPress sites.

Backwards Compatibility Drawbacks –

Can we have a look at the few things that potentially break a heritage application running on older versions of PHP?

    Deprecated Items Removed

There are a lot of deplored items, which have been removed as they have been deprecated for some time now and expectantly you are not using them. However, this might have a huge impact on legacy applications. Particularly, ASP-style tags like (<%; <%= and %>) were removed along with script tags (<script language="php">).

You should ensure that you are using the optional <?php tag instead. There are various other functions as well that were earlier deprecated such as split have also been detached in PHP 7.

When it comes to talking about ereg extension, it has been deprecated since PHP 5.3. It is must that it replaced with the PCRE extension (preg_* functions) that provides a lot of features. You can also make use of the mysqli extension and the mysqli_* functions instead for a direct migration.

Uniform Changeable Syntax –

At the time of evaluating variable expressions, the uniform variable syntax is mainly meant to solve a series of discrepancy. You can consider the below mentioned code:

<?php
class Person
{
    public $name = 'Erika';
    public $job = 'Developer Advocate';
}
    $person = new Person();
    $property = [ 'first' => 'name', 'second' => 'info' ];
    echo "\nMy name is " . $person->$property['first'] . "\n\n";
?>

The expression $person->$property[‘first’] is estimated as $ person->{$property['first']} in PHP 5. It will be understand as $person->name, providing you the result “My name is Erika” in practical terms. It shows clear inconsistencies with the normal expression evaluation order that is left to right even if it is an edge case.

However, an instant way to fix this issue is by openly defining the evaluation order with the help of curly braces that will give guarantee the same behavior on both PHP 5 and PHP 7.
All credit goes to the new uniform left-to-right variable syntax as there are lots of expressions earlier treated as unacceptable will now become valid. Consider the following class in order to illustrate this new behavior:

<?php
class Person
{
    public static $company = 'DigitalOcean';
    public function getFriends()
    {
        return [
            'erika' => function () {
                return 'Elephpants and Cats';
            },
            'sammy' => function () {
                return 'Sharks and Penguins';
            }
        ];
    }
    public function getFriendsOf($someone)
    {
        return $this->getFriends()[$someone];
    }
    public static function getNewPerson()
    {
        return new Person();
    }
}
?>

We are also capable of developing nested associations and different combinations between operators:

<?php
    $person = new Person();
    echo "\n" . $person->getFriends()['erika']() . "\n\n";
    echo "\n" . $person->getFriendsOf('sammy')() . "\n\n";
?>

This clip will give us a parse error on PHP 5, but works as expected on PHP 7.

Similarly, nested static access is also possible:

<?php
    echo "\n" . $person::getNewPerson()::$company . "\n\n";
?>

This would provide us the classic T_PAAMAYIM_ NEKUDOTAYIM syntax error in PHP 5.

Incurable Error With Multiple "Default" Clauses

Again, it is a border case and it is more about logic errors in your code. There is no use for multiple default clauses in a switch; however, it never caused any problem. It can be quite difficult to detect the mistake. The last default would be used in PHP 5, but when it comes to PHP 7, one will not get a Fatal Error: Switch statements may also contain one default clause.

New Language Features

Now, here is the best part – Let's have a look at the most amazing features, which will be obtainable when you upgrade to PHP 7.

New Operators –

The all new PHP 7 comes with two shiny new operators: the spaceship and the null coalesce operator. The spacecraft operator (<=>) that is also known as combined comparison operator, which can be used to make your chained comparison more concise.

Consider the following expression:
$a <=> $b

Above mentioned expression can evaluate to -1 if $a is smaller than $b, 0 if $a equals $b, and 1 if $b is greater than $a. Basically, it is a shortcut for the following expression:

$b, 0 if $a equals $b, and 1 if $b is greater than $a.

For a common use case, the null coalesce operator (??) that also works as a shortcut for a common use case: a conditional attribution that checks if a value is set before using it. Usually, you can do something like this in PHP 5:

<?php
    $a = isset($b) ? $b : "default";
?>

With the null coalesce operator in PHP 7, we can simply use:
<?php
$a = $b ?? "default";
?>

Scalar Type Hints

The most discussed new feature is coming with PHP 7 as scalar type hints will make it possible to use integers, strings, Booleans, floats as type hints for functions and methods.

By default, scalar type hints are non-restrictive that means if you pass a float value to an integer parameter, it will just force it to int without generating any errors or warnings.

However, it is also possible to allow a strict mode, which will throw errors at the time of wrong type is passed as an argument. Have a look at the following code:
<?php
    function double(int $value)
    {
        return 2 * $value;
    }
    $a = double("5");
    var_dump($a);
?>

Return Type Hints

One major and new feature that comes with PHP 7 is the capability to define the return type of methods and functions. It performs as a same fashion as scalar type hints in spite of coercion and strict mode:

<?php
    function a() : bool
    {
        return 1;
    }
    var_dump(a());
?>

Without any warnings, this snippet will run and the returned value will be transformed to bool mechanically. In case, if you are allowing strict mode, you can get a fatal error instead:

Fatal error: Uncaught TypeError: Return value of a() must be of the type boolean, integer returned

One more time, you should notice that these errors can really be exceptions, which can be caught and handled using try/catch blocks. It is also necessary to highlight that one can make use of any valid type hint, not only scalar types.

What’s Coming Next?

The all new PHP 7’s timeline shows a steady release in mid-October. However, the company is on release candidate cycles and a beta version is already obtainable for tests.

You can check out the RFC with all the changes coming with PHP 7 for more information.

Stay connected with us to get more information on PHP 7 and its incredible new solutions that will amaze you with its performance. Moreover, you can also get in touch with our experienced PHP developer, who can give best solutions to you.


SOURCE: phpdevelopmentsolutions.blogspot.in

Friday, July 24

PHP Singleton pattern for a database class

An example of how you would implement a Singleton pattern for a database class can be seen below:

<?php
class Database implements Singleton {
    private static $instance;
    private $pdo;

    private function __construct() {
        $this->pdo = new PDO(
            "mysql:host=localhost;dbname=database",
            "user",
            "password"
        );
    }

    public static function getInstance() {
        if(self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance->pdo;
    }
}
?>
You would make use of the class in the following manner:

<?php
$db = Database::getInstance();
// $db is now an instance of PDO
$db->prepare("SELECT ...");

// ...

$db = Database::getInstance();
// $db is the same instance as before
?>

And for reference, the Singleton interface would look like:
<?php
interface Singleton {
    public static function getInstance();
}
?>

Write a class that implements singleton pattern PHP.

In the singleton pattern a class can distribute one instance of itself to other classes.

<?php

/*
 *   Singleton classes
 */
class BookSingleton {
    private $author = 'Gamma, Helm, Johnson, and Vlissides';
    private $title  = 'Design Patterns';
    private static $book = NULL;
    private static $isLoanedOut = FALSE;

    private function __construct() {
    }

    static function borrowBook() {
      if (FALSE == self::$isLoanedOut) {
        if (NULL == self::$book) {
           self::$book = new BookSingleton();
        }
        self::$isLoanedOut = TRUE;
        return self::$book;
      } else {
        return NULL;
      }
    }

    function returnBook(BookSingleton $bookReturned) {
        self::$isLoanedOut = FALSE;
    }

    function getAuthor() {return $this->author;}

    function getTitle() {return $this->title;}

    function getAuthorAndTitle() {
      return $this->getTitle() . ' by ' . $this->getAuthor();
    }
  }

class BookBorrower {
    private $borrowedBook;
    private $haveBook = FALSE;

    function __construct() {
    }

    function getAuthorAndTitle() {
      if (TRUE == $this->haveBook) {
        return $this->borrowedBook->getAuthorAndTitle();
      } else {
        return "I don't have the book";
      }
    }

    function borrowBook() {
      $this->borrowedBook = BookSingleton::borrowBook();
      if ($this->borrowedBook == NULL) {
        $this->haveBook = FALSE;
      } else {
        $this->haveBook = TRUE;
      }
    }

    function returnBook() {
      $this->borrowedBook->returnBook($this->borrowedBook);
    }
  }

/*
 *   Initialization
 */

  writeln('BEGIN TESTING SINGLETON PATTERN');
  writeln('');

  $bookBorrower1 = new BookBorrower();
  $bookBorrower2 = new BookBorrower();

  $bookBorrower1->borrowBook();
  writeln('BookBorrower1 asked to borrow the book');
  writeln('BookBorrower1 Author and Title: ');
  writeln($bookBorrower1->getAuthorAndTitle());
  writeln('');

  $bookBorrower2->borrowBook();
  writeln('BookBorrower2 asked to borrow the book');
  writeln('BookBorrower2 Author and Title: ');
  writeln($bookBorrower2->getAuthorAndTitle());
  writeln('');

  $bookBorrower1->returnBook();
  writeln('BookBorrower1 returned the book');
  writeln('');

  $bookBorrower2->borrowBook();
  writeln('BookBorrower2 Author and Title: ');
  writeln($bookBorrower1->getAuthorAndTitle());
  writeln('');

  writeln('END TESTING SINGLETON PATTERN');

  function writeln($line_in) {
    echo $line_in.'<br/>';
  }
?>

Output

BEGIN TESTING SINGLETON PATTERN


BookBorrower1 asked to borrow the book
BookBorrower1 Author and Title:
Design Patterns by Gamma, Helm, Johnson, and Vlissides


BookBorrower2 asked to borrow the book
BookBorrower2 Author and Title:
I don't have the book


BookBorrower1 returned the book


BookBorrower2 Author and Title:
Design Patterns by Gamma, Helm, Johnson, and Vlissides


END TESTING SINGLETON PATTERN

Tuesday, July 14

Get Just The Path from a Request in PHP


It can be a little tricky to get just the path of a request in PHP.
$_SERVER['REQUEST_URI'] includes the query string.
$_SERVER['SCRIPT_NAME'] may return index.php instead of the request if you’re using a CMS like WordPress which rewrites URLs.

The most reliable method I’ve found for returning only the path without the query string uses PHP’s built in parse_url() function:

<?php

    $path_only = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

?>