Tuesday, 19 January 2016

PHP 7 new features

PHP 7 new features

Following are PHP 7 new features

  1. Scalar type declarations: In this we can declare what type of argument will be accepted by functions.
    function sumOfInts(int ...$all_ints){ /** It will accept only integers **/
        return array_sum($all_ints);
    }
    echo sumOfInts(2, 3); //5
    echo sumOfInts(2, '3', '5'); //10
    echo sumOfInts(2, '3', 'string'); //Error: Uncaught TypeError: Argument 3 passed to sumOfInts() must be of the type integer, string given
    
  2. Return type declarations : In this we can declare what what will be the datatype from functions.
    function sumOfInts(int ...$all_ints):int
    {
        return array_sum($all_ints);
    }
    echo sumOfInts(2, 3); //5
    echo sumOfInts(2, '3', '5'); //10
    
    Here if function "sumOfInts" return an string OR Array, it will give error.
  3. Null coalescing operator (??) have been added.
    $userId = $_GET['user_id'] ?? '0';
    is equivalent to
    $userId = isset($_GET['user_id']) ? $_GET['user_id'] : '0';
  4. Spaceship operator :The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1
    echo 1 <=> 1; // 0
    echo 1 <=> 2; // -1
    echo 2 <=> 1; // 1
    
  5. define() updates: Now you can add array.
    define('CLIENTS', [
        'client 1',
        'client 2',
        'client 3'
    ]);
    
    echo CLIENTS[1];//client 2
    
  6. Unicode codepoint escape syntax
    echo "\u{aa}";
    echo "\u{9999}";
  7. Closure::call Temporarily binding an object scope to a closure and invoking it.
    class A {private $x = 1;}
    $getX = function() {return $this->x;};
    echo $getX->call(new A);
  8. unserialize updates: Provide better security when unserializing objects on untrusted data and prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.
    $data = unserialize($searilizedData, ["allowed_classes" => ["MyClass", "MyClass2"]]);
  9. list() function updates: Now list() can unpack the object also. Earlier it unpack int, float, string and array only.
  10. session_start() function updates:
    Now you can pass array-options in this function. For Example:
    session_start([
        'cache_limiter' => 'private',
        'read_and_close' => true,
    ]);
  11. intdiv() new function It performs an integer division of its operands and returns it. For Example:
    echo intdiv(100, 3); //33
  12. use updations Classes, functions and constants being imported from the same namespace can now be grouped together in a single use statement Below both are Same.
    use some\namespace\ClassA;
    use some\namespace\ClassB;
    use some\namespace\ClassC as C;
    OR
    use some\namespace\{ClassA, ClassB, ClassC as C};
  13. CSPRNG Functions i.e. random_bytes() and random_int()
    $bytes = random_bytes(5);
    var_dump(bin2hex($bytes)); //string(10) "385e33f741"
    var_dump(random_int(1, 100));//1-100
  14. Generator delegation: Generators can now delegate to another generator using yield, Traversable object/array automatically.
    function func1()
    {
        yield 1;
        yield 2;
        yield from func2();
    }
    
    function func2()
    {
        yield 3;
        yield 4;
    }
    
    foreach (func1() as $val)
    {
        echo $val, PHP_EOL;
    }
    /** Output 
    1
    2
    3
    4
    Output **/
    

Monday, 18 January 2016

Database Query in Zend framework 2

Database Query in Zend framework 2

Question: How to set database connection in Config file?
Create local.php file in config/autoload/ and following code .
return array(
'db' => array(
    'driver'         => 'Pdo',
    'dsn'            => 'mysql:dbname=mydb;host=localhost',
    'username'       =>'',
    'password'      =>'',
    'driver_options' => array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
    ),
),
'service_manager' => array(
    'aliases' => array(
'db' => 'Zend\Db\Adapter\Adapter',
)
));

In controller,you can get database object
$dbObj = $this->getServiceLocator()->get('db');



Question: How to connect mysql in ZF2?
$adapter = new Zend\Db\Adapter\Adapter(array(
    'driver' => 'Mysqli',
    'database' => 'mydb',
    'username' => 'root',
    'password' => ''
 ));



Question: What are different database driver provided by ZF2 ?
  1. Pdo_Mysql: MySQL through the PDO extension
  2. Pdo_Sqlite: SQLite though the PDO extension
  3. Pdo_Pgsql: PostgreSQL through the PDO extension
  4. Mysqli: The ext/mysqli driver
  5. Pgsql: The ext/pgsql driver
  6. Sqlsrv: The ext/sqlsrv driver



Question: Can we create a new Adaper for database connection? If yes, How?
With use of following you can create your own Database adapter.
use Zend\Db\Adapter\Platform\PlatformInterface;
use Zend\Db\ResultSet\ResultSet;
See Example:
use Zend\Db\Adapter\Platform\PlatformInterface;
use Zend\Db\ResultSet\ResultSet;

class Zend\Db\Adapter\Adapter {
    public function __construct($driver, PlatformInterface $platform = null, ResultSet $queryResultSetPrototype = null)
}



Question: How to custom query in zend framework 2?
$adapter->query('SELECT * FROM `users` WHERE `embid` = ? and name like "%?%" ', array(5,'rajesh'));



Question: How to join two tables in Zend Framework2?
use Zend\Db\Sql\Select();
use Zend\Db\ResultSet\ResultSet();

$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))
   ->join('profile', 'profile.user_id' = 'users.id'); //This is inner Join

$statement = $dbAdapter->createStatement();
$select->prepareStatement($dbAdapter, $statement);
$driverResult = $statment->execute();

$resultset = new ResultSet();
$resultset->initialize($driverResult); // can use setDataSource() for older ZF2 versions.

foreach ($resultset as $row) {
print_r($row);
}



Question: How to use Expression with query in ZF2?
new \Zend\Db\Sql\Expression("NOW()");



Question:How to Add Sub Query in ZF2
$sql = new Sql($this->_adapter);
$mainSelect = $sql->select()->from('table1');
$subQry = $sql->select()
        ->from('md_type')
        ->columns(array('orderCount' => new \Zend\Db\Sql\Expression('COUNT(table2.parent_id)')))
        ->where('table2.parent_id = table1.id');
$mainSelect->columns(
        array(
            'id', 
            'total' => new \Zend\Db\Sql\Expression('?', array($subQry)),
        )
);

$statement = $sql->prepareStatementForSqlObject($mainSelect);
$comments = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($comments)
foreach ($resultset as $row) {
print_r($row);
}



Question: How to use Group By in ZF2
$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))->group('users.first_name');



Question: How to use having clause in ZF2
$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name','similar_name'=>'count(first_name)'))->group('users.first_name')->having('count(first_name)>1');



Question: How to use Order By in ZF2

$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))->order('users.first_name asc');



Question: How to use limit in ZF2

$select = new Select();
$select->from('users')
   ->columns(array('users.*', 'u_name' => 'users.first_name'))->order('users.first_name asc')->limit(20);