Saturday, April 21, 2018

Grails on Groovy > @Transactional does not rollback on checked exceptions

We’re using the Spring Framework in most of our grails applications to manage database transaction.
One of the big advantages is the the declarative transaction handling using the @Transactional attribute.
import org.springframework.transaction.Transactional;
 
@Transactional
public class MyService {
  List exec () {
    
  }
}
That simple annoation on class managed by a Spring ApplicationContext causes all method calls onto that service to be bound to a transaction. The transaction is committed after the method call has left the service again and it’s rollbacked for the case an exception is thrown
But be careful: Only unchecked exceptions (that is, subclasses of java.lang.RuntimeException) are rollbacked by default. For the case, a checked exception is thrown, the transaction will be committed!
And that customization can be done very easily by just adding the parameter rollBackFor to the @Transactional attribute:
import org.springframework.transaction.Transactional;
 
@Transactional(rollbackFor = Exception.class)
public class MyService {
  List exec () {
    
  }
}

Friday, April 20, 2018

Extending from Laravel 5 core - SqlServerConnection | Extending The Connection Class In Laravel

The first thing the ConnectionFactory::createConnection() method does is to check if the db.connection.{$driver} alias is bound, and if so, it returns that connection object. If it is not bound, it returns the base connection object (Illuminate\Database\MySqlServerConnection for the mysql driver)
Therefore, all you need to do to use your own custom connection is to bind the db.connection.mysql alias to your custom MySqlServerConnection class
You can create a new service provider in which to do this, or you can just add the line to your existing AppServiceProvider
<?php
namespace App\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);
    }

    public function register() {
        $this->app->bind('db.connection.mysql', \App\Database\MySqlConnection::class);
    }
}
Remember that there may be two methods in any ServiceProvider, first call "register" method of each ServiceProvider listed and after that "boot" method called each ServiceProvider listed in "config/app.php" in providers section.
<?php
return [
    'providers' => [
        App\Providers\EventServiceProvider::class,
        App\Providers\AppServiceProvider::class
    ]
];
You have to create a MySQL connection class \App\Database\MySqlConnection
<?php
namespace App\Database;

use Illuminate\Database\MySqlConnection as ParentMySqlConnection;

class MySqlConnection extends ParentMySqlConnection {
    public function select($query, $bindings = [], $useReadPdo = true) {
        return parent::select($query, $bindings, $useReadPdo);
    }
}
So its completed, MySqlConnection is now extended with our own connection class.
So you can now anything do with your custom connection class.

Thursday, April 19, 2018

How to get current time in milliseconds in PHP | Converting microtime() to milliseconds/seconds

The short answer is
$milliseconds = round(microtime(true) * 1000);
Use microtime(). This function returns a string separated by a space. The first part is the fractional part of seconds, the second part is the integral part. Pass in true to get as a number:
var_dump(microtime()); // string(21) "0.89115400 1283846202"
var_dump(microtime(true)); // float(1283846202.89)
64 bits platforms only!
function milliseconds() {
    $mt = explode(' ', microtime());
    return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
}

Wednesday, April 11, 2018

Using PHP's glob() function to find files in a directory | Filter files in directory | Regex filter files in directory

The examples below look at a directory with the following, the same example directory as used in the read through directory post
To find all the files in the directory /path/to/directory with a .txt file extension, you can do this:
$files = glob("/path/to/directory/*.txt");
Array
(
    [0] => /path/to/directory/bar.txt
    [1] => /path/to/directory/foo.txt
    [2] => /path/to/directory/link2foo.txt
)
There are flags which can be passed as a second optional parameter. One of these is GLOB_BRACE which means that e.g. {jpg,gif,png} will be expanded to match jpg, gif and png which can be useful if you need to look for a particular set of files by their extension, in this example for image files
$files = glob("/path/to/directory/*.{jpg,gif,png}", GLOB_BRACE);
Array
(
    [0] => /path/to/directory/1.jpg
    [1] => /path/to/directory/2.gif
    [2] => /path/to/directory/3.png
)

Can a PHP script execute common code before exit() | register_shutdown_function | PHP execute a piece of code before process terminated by exit() or die() method

Registers a callback to be executed after script execution finishes or exit() is called.
Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.
<?php
function shutdown()
{
    // This is our shutdown function, in 
    // here we can do any last operations
    // before the script is complete.

    echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>
<?php 
namespace App\Test;

class CallbackClass { 
    function CallbackFunction() { 
        // refers to $this 
    } 

    function StaticFunction() { 
        // doesn't refer to $this 
    } 
} 

function NonClassFunction() { 
} 
?> 

there appear to be 3 ways to set a callback function in PHP (using register_shutdown_function() as an example): 

1: register_shutdown_function('NonClassFunction'); 

2: register_shutdown_function(array('\App\Test\CallbackClass', 'StaticFunction')); 

3: $o =& new CallbackClass(); 
   register_shutdown_function(array($o, 'CallbackFunction')); 

Friday, April 6, 2018

How to Make Async Requests in PHP | Methods for synchronous processes in PHP | Making synchronous function call in PHP | Make sure same function will not execute parallel


<?php
function executeSync($key, $closure) {
    $sem = getSemGetCustom($key);
    if(getSemAcquireCustom($sem)) {
        $closure();

        getSemReleaseCustom($sem);
    }
    else {
        throw new \Exception("Processing");
    }
}

function getSemGetCustom($key) {
    return fopen(sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($key) . '.sem', 'w+');
}

function getSemAcquireCustom($sem) {
    return flock($sem, LOCK_EX);
}

function getSemReleaseCustom($sem) {
    return flock($sem, LOCK_UN);
}

function logText($text) {
    file_put_contents('data.txt', $text.PHP_EOL , FILE_APPEND | LOCK_EX);
}

$id = $_GET["id"];
$closure = function() use($id) {
    logText("STARTING-$id");
    sleep(1);
    logText("FINISHED-$id");
};

executeSync("KEY", $closure);
Or if you want to set timeout for lock
<?php
public static function lockAndExecute($key, Closure $closure, $timeout_seconds = 5) {
    $file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($key) . '.tmp';
    $handle = fopen($file, 'w+');
    while (!flock($handle, LOCK_EX | LOCK_NB)) {
        usleep(1000 * 249);
        $timeout_seconds = $timeout_seconds - 0.25;
        if ($timeout_seconds <= 0) {
            throw new Exception("Unable to acquire lock");
        }
    }
    try {
        return $closure();
    }
    finally {
        flock($handle, LOCK_UN);
        fclose($handle);
    }
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Custom Popup</title>
    <meta name="viewport" content="user-scalable=yes, initial-scale=1, maximum-scale=1,minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi"/>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.get("exec.php", { id: 1 });
            $.get("exec.php", { id: 2 });
            $.get("exec.php", { id: 3 });
            $.get("exec.php", { id: 4 });
            $.get("exec.php", { id: 5 });
            $.get("exec.php", { id: 6 });
            $.get("exec.php", { id: 7 });
            $.get("exec.php", { id: 8 });
            $.get("exec.php", { id: 9 });
            $.get("exec.php", { id: 10 });
        });
    </script>
</head>
<body>

</body>
</html>

You can see that function "executeSync" executing synchronously.