Reputation: 3072
I have a method that syncs and updates a database based on an API service. The connection to the API is made via Socket (TCP/IP). The API has a service to return all the ids of the updated items and another to get an item with the updated data. So, i created a sync method that gets the list of updated item ids, iterates the list and updates each item. Since i have to make a socket connection inside the loop to get the item details, this process can take some time depending on the number os items to update. For that reason i would like to allow the client to cancel/stop this process if desired.
Is this possible to accomplish with my current method? Or should i do the items iteration in the client side and change the API to update one item at each request?
The client app is in Angular and the API in PHP.
UPDATE: Example of the current sync method:
public static function syncItems()
{
$response = -1;
try {
//get all updated item ids from api
$updatedItemIds = self::getUpdatedItemIDs(); //connection to tcp/ip socket
if (isset($updatedItemIds)) {
$totalItems = count($updatedItemIds);
$updatedIems = 0;
//iterate all ids and get the item details
foreach ($updatedItemIds as $id) {
//get updated item data from api
$updatedItem = self::getItemDetails($id); //connection to tcp/ip socket
if (isset($updatedItem)) {
//get local version o the item
$item = Item::find($id);
//if item doesn't exist create a new one
if (!isset($item)) {
$item = new item();
}
//update item data
$item->id = $updatedItem->id
$item->name = $updatedItem->name;
$item->description = $updatedItem->description;
//save or update item details in DB
if ($item->save()) {
//increment updated items
$updateditems++;
} else {
//not saved
}
} else {
//not set
}
}
$response = $totalitems - $updateditems;
}
else
{
//no items to sync...
}
} catch (Exception $ex) {
//ooppsss!
}
return $response;
}
Upvotes: 1
Views: 320
Reputation: 3260
I just thought of a solution. You'd need to use sessions.
You'd want to set $_SESSION['halt'] = false
before the foreach()
started.
foreach ($updatedItemIds as $id) {
if($_SESSION['halt'] === true)) {
$_SESSION['halt'] = false; //set back to false immediate.
die;
}
//The socket connection would never get made if the above evaluated to true.
$updatedItem = self::getItemDetails($id); //connection to tcp/ip socket
}
Have a button on the user end pointing to another script which just sets $_SESSION['halt'] == true
when clicked.
You could even set a pause in your script to slow it down and give the user more time to react, etc. if you want to.
Upvotes: 1