Using ZeroMQ (PHP-ZMQ) for loop operations - php

I'm trying to use heavy resource content loop operation with ZeroMQ (PHP-ZMQ) via tcp protocol.
I've got below code so far:
class SJB_Miscellaneous_SendNotifications extends SJB_Function
{
public function execute()
{
try{
set_time_limit(0);
$i18n = SJB_I18N::getInstance();
$lang = $i18n->getLanguageData($i18n->getCurrentLanguage());
$current_date = strftime($lang['date_format'], time());
// Send Search Notifications
$saved_searches = SJB_SavedSearches::getAutoNotifySavedSearches();
// echo "<pre>"; print_r($saved_searches); echo "</pre>"; exit;
$listing = new SJB_Listing();
$notified_saved_searches_sid = array();
$notificationsLimit = (int) SJB_Settings::getSettingByName('num_of_listings_sent_in_email_alerts');
/* ZeroMQ implementation */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ, "MySock1");
$queue->connect("tcp://127.0.0.1:5555");
/* Assign socket 1 to the queue, send and receive */
$time = time();
$queue->send(json_encode($saved_searches));
// echo $queue->recv();
// exit;
$count = 1;
// array_shift($saved_searches);
$server = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REP);
$server->bind("tcp://127.0.0.1:5555");
$msg = $server->recv();
$saved_searches = json_decode($msg, true);
// echo "<pre>"; var_dump($saved_searches); echo "</pre>";
// exit;
foreach ($saved_searches as $saved_search) {
$searcher = new SJB_ListingSearcher();
$listing->addActivationDateProperty();
$search_data = unserialize($saved_search['data']);
$search_data['active']['equal'] = 1;
$datearr = explode('-', $saved_search['last_send']);
$saved_search['last_send'] = strftime($lang['date_format'], mktime(0, 0, 0, $datearr[1], $datearr[2], $datearr[0]));
$search_data['activation_date']['not_less'] = $saved_search['last_send'];
$search_data['activation_date']['not_more'] = $current_date;
$listing_type_sid = 0;
if ($search_data['listing_type']['equal']) {
$listing_type_id = $search_data['listing_type']['equal'];
$listing_type_sid = SJB_ListingTypeManager::getListingTypeSIDByID($listing_type_id);
if (SJB_ListingTypeManager::getWaitApproveSettingByListingType($listing_type_sid))
$search_data['status']['equal'] = 'approved';
}
// echo "<pre>"; echo $saved_search['user_sid']; print_r($listing_type_id); echo "</pre>"; exit;
$id_alias_info = $listing->addIDProperty();
$username_alias_info = $listing->addUsernameProperty();
$listing_type_id_info = $listing->addListingTypeIDProperty();
$aliases = new SJB_PropertyAliases();
$aliases->addAlias($id_alias_info);
$aliases->addAlias($username_alias_info);
$aliases->addAlias($listing_type_id_info);
$search_data['access_type'] = array(
'accessible' => $saved_search['user_sid'],
);
$criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($search_data, $listing);
$searcher->found_object_sids = array();
$searcher->setLimit($notificationsLimit);
$sorting_fields = array('CityRegion' => 'ASC');
$found_listings_ids = $searcher->getObjectsSIDsByCriteria($criteria, $aliases, $sorting_fields);
// echo "<pre>"; var_dump($found_listings_ids); echo "</pre>";
if (count($found_listings_ids)) {
$saved_search['activation_date'] = $saved_search['last_send'];
if (SJB_Notifications::sendUserNewListingsFoundLetter($found_listings_ids, $saved_search['user_sid'], $saved_search, $listing_type_sid)) {
SJB_Statistics::addStatistics('sentAlert', $listing_type_sid, $saved_search['sid']);
SJB_DB::query('UPDATE `saved_searches` SET `last_send` = CURDATE() WHERE `sid` = ?n', $saved_search['sid']);
}
$notified_saved_searches_sid[] = $saved_search['sid'];
}
echo nl2br($count."\n");
$count++;
}
// To be entered from task_scheduler.php
$expired_contracts_id = null; $expired_listings_id = null;
$template_processor = SJB_System::getTemplateProcessor();
$template_processor->assign('expired_listings_id', null);
$template_processor->assign('deactivated_listings_id', null);
$template_processor->assign('expired_contracts_id', null);
$template_processor->assign('notified_saved_searches_id', $notified_saved_searches_sid);
$scheduler_log = $template_processor->fetch('task_scheduler_log.tpl');
if ($log_file = #fopen('task_scheduler.log', 'a+')) {
fwrite($log_file, $scheduler_log);
fclose($log_file);
}
SJB_DB::query('INSERT INTO `task_scheduler_log`
(`last_executed_date`, `notifieds_sent`, `expired_listings`, `expired_contracts`, `log_text`)
VALUES ( NOW(), ?n, ?n, ?n, ?s)',
count($notified_saved_searches_sid), count($expired_listings_id), count($expired_contracts_id), $scheduler_log);
} catch(Exception $e){
echo $e->getMessage();
}
}
} // END class SJB_Miscellaneous_SendNotifications extends SJB_Function
Is there a good way to utilise ZeroMQ for this type of operation where I want to free loop operations especially when it reaches $saved_searches foreach loop?

Related

how to use dreamscape api in nodejs for check domain name

I have already work this in php. Here is my working code:
$request = array(
'DomainNames' => $domain_names
);
$response = dreamScapeAPI('DomainCheck', $request);
$available = false;
$alt_domains = array(); // Alternative to user's expected domain names
if (!is_soap_fault($response)) {
// Successfully checked the availability of the domains
if (isset($response->APIResponse->AvailabilityList)) {
$availabilityList = $response->APIResponse->AvailabilityList;
foreach ($availabilityList as $list) {
if ($list->Available){
if ($domain == $list->Item) {
$available = true; // user prefered domain found
}
else {
$alt_domains[] = $list->Item;
}
}
}
}
else {
$error = $response->APIResponse->Errors;
foreach ($error as $e) {
$api_error = $e->Message;
//echo $e->Item . ' - ' . $e->Message . '<br />';
}
}
}
function dreamScapeAPI($method, $data = null) {
$reseller_api_soap_client = "";
$soap_location = 'http://soap.secureapi.com.au/API-2.1';
$wsdl_location = 'http://soap.secureapi.com.au/wsdl/API-2.1.wsdl';
$authenticate = array();
$authenticate['AuthenticateRequest'] = array();
$authenticate['AuthenticateRequest']['ResellerID'] = '**';
$authenticate['AuthenticateRequest']['APIKey'] = '**';
//convert $authenticate to a soap variable
$authenticate['AuthenticateRequest'] = new SoapVar($authenticate['AuthenticateRequest'], SOAP_ENC_OBJECT);
$authenticate = new SoapVar($authenticate, SOAP_ENC_OBJECT);
$header = new SoapHeader($soap_location, 'Authenticate', $authenticate, false);
$reseller_api_soap_client = new SoapClient($wsdl_location, array('soap_version' => SOAP_1_2, 'cache_wsdl' => WSDL_CACHE_NONE));
$reseller_api_soap_client->__setSoapHeaders(array($header));
$prepared_data = $data != null ? array($data) : array();
try {
$response = $reseller_api_soap_client->__soapCall($method, $prepared_data);
} catch (SoapFault $response) { }
return $response;
}
I tried with this : https://github.com/dan-power/node-dreamscape
But domain search can not work properly. Mainly, I want it on nodejs using nodejs dreamscape api but this method is not available on nodejs.
Here is my working demo: click here

Creating default object from empty value ( stdClass? )

The script run good, but only when I fetching out the groups of the user, it's says:
SteamUser.php (132): Creating default object from empty value
function getProfileData() {
//Set Base URL for the query:
if(empty($this->vanityURL)) {
$base = "http://steamcommunity.com/profiles/{$this->userID}/?xml=1";
} else {
$base = "http://steamcommunity.com/id/{$this->vanityURL}/?xml=1";
}
try {
$content = SteamUtility::fetchURL($base);
if ($content) {
$parsedData = new SimpleXMLElement($content);
} else {
return null;
}
} catch (Exception $e) {
//echo "Whoops! Something went wrong!\n\nException Info:\n" . $e . "\n\n";
return null;
}
if(!empty($parsedData)) {
$this->steamID64 = (string)$parsedData->steamID64;
$this->steamID = (string)$parsedData->steamID;
$this->stateMessage = (string)$parsedData->stateMessage;
$this->visibilityState = (int)$parsedData->visibilityState;
$this->privacyState = (string)$parsedData->privacyState;
$this->avatarIcon = (string)$parsedData->avatarIcon;
$this->avatarMedium = (string)$parsedData->avatarMedium;
$this->avatarFull = (string)$parsedData->avatarFull;
$this->vacBanned = (int)$parsedData->vacBanned;
$this->tradeBanState = (string)$parsedData->tradeBanState;
$this->isLimitedAccount = (string)$parsedData->isLimitedAccount;
$this->onlineState = (string)$parsedData->onlineState;
$this->inGameServerIP = (string)$parsedData->inGameServerIP;
//If their account is public, get that info:
if($this->privacyState == "public") {
$this->customURL = (string)$parsedData->customURL;
$this->memberSince = (string)$parsedData->memberSince;
$this->steamRating = (float)$parsedData->steamRating;
$this->hoursPlayed2Wk = (float)$parsedData->hoursPlayed2Wk;
$this->headline = (string)$parsedData->headline;
$this->location = (string)$parsedData->location;
$this->realname = (string)$parsedData->realname;
$this->summary = (string)$parsedData->summary;
}
//If they're in a game, grab that info:
if($this->onlineState == "in-game") {
$this->inGameInfo = array();
$this->inGameInfo["gameName"] = (string)$parsedData->inGameInfo->gameName;
$this->inGameInfo["gameLink"] = (string)$parsedData->inGameInfo->gameLink;
$this->inGameInfo["gameIcon"] = (string)$parsedData->inGameInfo->gameIcon;
$this->inGameInfo["gameLogo"] = (string)$parsedData->inGameInfo->gameLogo;
$this->inGameInfo["gameLogoSmall"] = (string)$parsedData->inGameInfo->gameLogoSmall;
}
//Any weblinks listed in their profile:
if(!empty($parsedData->weblinks)) {
$this->weblinks = array();
$i = 0;
foreach ($parsedData->weblinks->weblink as $weblink) {
$this->weblinks[$i]->title = (string)$weblink->title;
$this->weblinks[$i]->link = (string)$weblink->link;
$i++;
}
}
if(!empty($parsedData->groups)) {
$this->groups = array();
$i = 0;
foreach ($parsedData->groups->group as $group) {
$this->groups[$i]->groupID64 = (string)$group->groupID64; // row 132 in script
$this->groups[$i]->groupName = (string)$group->groupName;
$this->groups[$i]->groupURL = (string)$group->groupURL;
$this->groups[$i]->headline = (string)$group->headline;
$this->groups[$i]->summary = (string)$group->summary;
$this->groups[$i]->avatarIcon = (string)$group->avatarIcon;
$this->groups[$i]->avatarMedium = (string)$group->avatarMedium;
$this->groups[$i]->avatarFull = (string)$group->avatarFull;
$this->groups[$i]->memberCount = (string)$group->memberCount;
$this->groups[$i]->membersInChat = (string)$group->membersInChat;
$this->groups[$i]->membersInGame = (string)$group->membersInGame;
$this->groups[$i]->membersOnline = (string)$group->membersOnline;
$i++;
}
}
}
}
.
.
.
I already tried to using associative arrays, but didn't work; maybe with doing it all new. -_-
So, I can't set error_reporting(0) or ini_set at all.
I also used new stdClass() as a try. But I didn't get this running too.
You create an array.
$this->groups = array();
But in this array you donot create any object. You just use this array's elements (thoes are not initialized) as objects. You should add this line before your 132. row.
$this->groups[$i] = new Group();
Or something similar.
If you do not have Group class you should try
$this->groups[$i] = new stdClass();

Symfony with GeoIp2

HelloI need find city for ip, I install maxmind/GeoIP2-php and download file GeoLite2-City.mmdb 31mb GeoLite2-City.mmdb 2,2mb and create service AdditionalFunction and function getInfoIpCity, getInfoIpCountry and when developer registration I use this function like this:
$ip = $request->getClientIp();
$record = $hAid->getInfoIpCountry($ip);
$get_record = $hAid->getInfoIpCity($ip);
$record_coutry = $record->country->name;
I download GeoLite2-City-CSV_20150707/ and this file GeoLite2-City-Blocks-IPv4.csv 135.3 mb and in this file I find 176.241.128.0/20,690791,690791,,0,0,,50.4500,30.5233 If I have this file how I can find name city ? If I have in variable 50.4500,30.5233 and google know this is Kyiv how I get name city ?
and service:
class AdditionalFunction
{
private $rootDir;
public function setRootDir($rootDir)
{
$this->rootDir = $rootDir;
}
public function getInfoIpCountry($ip)
{
try {
$reader = new Reader($this->rootDir.'/data/GeoLite2-Country.mmdb');
$data = $reader->country($ip);
} catch (\Exception $e) {
$data = null;
}
return $data;
}
public function getInfoIpCity($ip)
{
try {
$reader = new Reader($this->rootDir.'/data/GeoLite2-City.mmdb');
$data = $reader->city($ip);
$m = $data->country->name;
$t = $data->country->isoCode;
$b = $data->mostSpecificSubdivision->name;
$c = $data->city->name;
} catch (\Exception $e) {
$data = null;
}
return $data;
}
}
coutry find right
but in dump I have $c = null, $b = null
why???? I need city
I solved my problem I use free base for maxmind but if city not found in this DB I use googlr aip and find city for latitude & longitude, this code:
public function getInfoIpCity($ip)
{
try {
$reader = new Reader($this->rootDir.'/data/GeoLite2-City.mmdb');
$data_geo = $reader->city($ip);
$name = $data_geo->country->name;
$isoCode = $data_geo->country->isoCode;
$mostSpecificSubdivision = $data_geo->mostSpecificSubdivision->name;
$data = $city = $data_geo->city->name;
$postal = $data_geo->postal->code; // '55455'
$latitude = $data_geo->location->latitude; // 50.45
$longitude = $data_geo->location->longitude;// 30.5233
if (is_null($data)){
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$latitude.','.$longitude.'&sensor=false';
$data = #file_get_contents($url);
$jsondata = json_decode($data,true);
if(is_array($jsondata )&& $jsondata ['status'] == "OK")
{
$addr = $jsondata ['results'][0]['address_components'][4]['long_name'];
$addr2 = $jsondata ['results'][0]['address_components'][4]['short_name'];
$addr3 = $jsondata ['results'][0]['address_components'][3]['long_name'];
}
$info = "Country: " . $addr . " | Region: " . $addr2 . " | City: " . $addr3;
$data = $addr3;
}
} catch (\Exception $e) {
$data = null;
}
return $data;
}

Php JSON Response Array

I have this php code. As you can see i query a mysql database through a function showallevents. I return a the $result to the $event variable. With the while loop i assign the values that i get from event to a response array and every time the loop happens the rows are stored in the data array. Surely i am failing somewhere because despite i am getting a correct number of responses all the values that i get at json are "null". Also it tells me something about JSONarray cannot be converted to jsonobject
if (isset($_POST['tag']) && $_POST['tag'] != '')
{
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'showallevents')
{
// Request type is show all events
// show all events
$event = $db->showallevents();
if ($event != false)
{
$data = array();
while($row = mysql_fetch_assoc($event))
{
$response["success"] = 1;
$response["uid"] = $event["uid"];
$response["event"]["date"] = $event["date"];
$response["event"]["hours"] = $event["hours"];
$response["event"]["store_name"] = $event["store_name"];
$response["event"]["event_information"] = $event["event_information"];
$response["event"]["event_type"] = $event["event_type"];
$response["event"]["Phone"] = $event["Phone"];
$response["event"]["address"] = $event["address"];
$response["event"]["created_at"] = $event["created_at"];
$response["event"]["updated_at"] = $event["updated_at"];
$data[]=$response;
}
echo json_encode($data);
}
else
{
// event not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Events not found";
echo json_encode($response);
}
}
else
{
echo "Access Denied";
}
}
?>
the DB_Functions.php
<?php
class DB_Functions
{
private $db;
//put your code here
// constructor
function __construct()
{
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct()
{
}
/**
* Select all events that are after yesterday.
*/
public function showallevents()
{
$result = mysql_query("SELECT * FROM events WHERE date >= CURDATE()");
return($result);
}
}
?>
ok the code that helped me put all data into an array was this
$data = array();
while($row = mysql_fetch_assoc($event))
{
$response["success"] = 1;
$response["event"]= $row;
$data[]=$response;
}
echo json_encode($data);
You've merged two independent pieces of code and wound up with a mess whose result is unclear.
You can create an associative array in two ways:
$array = (key=>value, key2=>value2);
You can also use:
$array[key]=value;
$array[key2]=value2;
Note that both 'key' and 'value' are simply variables; you can use strings there, or pass in a variable from someplace else.
When doing similar things, I use the following approach:
$response["success"] = 1;
$response["uid"] = $event["uid"];
$response["event"]["date"] = $event["date"];
$response["event"]["hours"] = $event["hours"];
$response["event"]["store_name"] = $event["store_name"];
$response["event"]["event_information"] = $event["event_information"];
$response["event"]["event_type"] = $event["event_type"];
$response["event"]["Phone"] = $event["Phone"];
$response["event"]["address"] = $event["address"];
$response["event"]["created_at"] = $event["created_at"];
$response["event"]["updated_at"] = $event["updated_at"];
$data[]=$response;
What is your $response variable?
In PHP to create associative arrays, you use => and not =
for example:
$array = ('key1' => 'value1', 'key2' => 'value2');
if you just want to return all the arrays, can you use mysql_fetch_assoc in stead of mysql_fetch_row?
if ($tag == 'showallevents')
{
// Request type is show all events
// show all events
$event = $db->showallevents();
if ($event != false)
{
$data = array();
while($row = mysql_fetch_assoc($event))
{
$data[] = $row;
echo json_encode($data);
}
else
{
// event not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Events not found";
echo json_encode($response);
}
}
else
{
echo "Access Denied";
}
}
?>

Cassandra with PHP - on call of cassandra-test.php I get "Call to undefined method CassandraClient::batch_insert()"

Im trying to make Cassandra run with PHP on Windows 7 at the moment.
I installed cassandra and thrift...
When I call the cassandra-test.php, I get the following error:
( ! ) Fatal error: Call to undefined method
CassandraClient::batch_insert() in
C:\xampp\htdocs\YiiPlayground\cassandra-test.php on line 75
Call Stack
# Time Memory Function Location
1 0.0014 337552 {main}( ) ..\cassandra-test.php:0
2 0.0138 776232 CassandraDB->InsertRecord(
) ..\cassandra-test.php:304
The cassandra-test.php looks as follows:
<?php
// CassandraDB version 0.1
// Software Projects Inc
// http://www.softwareprojects.com
//
// Includes
$GLOBALS['THRIFT_ROOT'] = 'C:/xampp/htdocs/Yii/kallaspriit-Cassandra-PHP-Client-Library/thrift';
//$GLOBALS['THRIFT_ROOT'] = realpath('E:/00-REGIESTART/Programme/Cassandra/thrift');
require_once $GLOBALS['THRIFT_ROOT'].'/packages/cassandra/Cassandra.php';
require_once $GLOBALS['THRIFT_ROOT'].'/packages/cassandra/cassandra_types.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php';
require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TFramedTransport.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php';
class CassandraDB
{
// Internal variables
protected $socket;
protected $client;
protected $keyspace;
protected $transport;
protected $protocol;
protected $err_str = "";
protected $display_errors = 0;
protected $consistency = 1;
protected $parse_columns = 1;
// Functions
// Constructor - Connect to Cassandra via Thrift
function CassandraDB ($keyspace, $host = "127.0.0.1", $port = 9160)
{
// Initialize
$this->err_str = '';
try
{
// Store passed 'keyspace' in object
$this->keyspace = $keyspace;
// Make a connection to the Thrift interface to Cassandra
$this->socket = new TSocket($host, $port);
$this->transport = new TFramedTransport($this->socket, 1024, 1024);
$this->protocol = new TBinaryProtocolAccelerated($this->transport);
$this->client = new CassandraClient($this->protocol);
$this->transport->open();
}
catch (TException $tx)
{
// Error occured
$this->err_str = $tx->why;
$this->Debug($tx->why." ".$tx->getMessage());
}
}
// Insert Column into ColumnFamily
// (Equivalent to RDBMS Insert record to a table)
function InsertRecord ($table /* ColumnFamily */, $key /* ColumnFamily Key */, $record /* Columns */)
{
// Initialize
$this->err_str = '';
try
{
// Timestamp for update
$timestamp = time();
// Build batch mutation
$cfmap = array();
$cfmap[$table] = $this->array_to_supercolumns_or_columns($record, $timestamp);
// Insert
$this->client->batch_insert($this->keyspace, $key, $cfmap, $this->consistency);
// If we're up to here, all is well
$result = 1;
}
catch (TException $tx)
{
// Error occured
$result = 0;
$this->err_str = $tx->why;
$this->Debug($tx->why." ".$tx->getMessage());
}
// Return result
return $result;
}
// Insert SuperColumn into SuperColumnFamily
// (Equivalent to RDMBS Insert record to a "nested table")
function InsertRecordArray ($table /* SuperColumnFamily */, $key_parent /* Super CF */,
$record /* Columns */)
{
// Initialize
$err_str = '';
try
{
// Timestamp for update
$timestamp = time();
// Build batch mutation
$cfmap = array();
$cfmap[$table] = $this->array_to_supercolumns_or_columns($record, $timestamp);
// Insert
$this->client->batch_insert($this->keyspace, $key_parent, $cfmap, $this->consistency);
// If we're up to here, all is well
$result = 1;
}
catch (TException $tx)
{
// Error occured
$result = 0;
$this->err_str = $tx->why;
$this->Debug($tx->why." ".$tx->getMessage());
}
// Return result
return $result;
}
// Get record by key
function GetRecordByKey ($table /* ColumnFamily or SuperColumnFamily */, $key, $start_from="", $end_at="")
{
// Initialize
$err_str = '';
try
{
return $this->get($table, $key, NULL, $start_from, $end_at);
}
catch (TException $tx)
{
// Error occured
$this->err_str = $tx->why;
$this->Debug($tx->why." ".$tx->getMessage());
return array();
}
}
// Print debug message
function Debug ($str)
{
// If verbose is off, we're done
if (!$this->display_errors) return;
// Print
echo date("Y-m-d h:i:s")." CassandraDB ERROR: $str\r\n";
}
// Turn verbose debug on/off (Default is off)
function SetDisplayErrors($flag)
{
$this->display_errors = $flag;
}
// Set Consistency level (Default is 1)
function SetConsistency ($consistency)
{
$this->consistency = $consistency;
}
// Build cf array
function array_to_supercolumns_or_columns($array, $timestamp=null)
{
if(empty($timestamp)) $timestamp = time();
$ret = null;
foreach($array as $name => $value) {
$c_or_sc = new cassandra_ColumnOrSuperColumn();
if(is_array($value)) {
$c_or_sc->super_column = new cassandra_SuperColumn();
$c_or_sc->super_column->name = $this->unparse_column_name($name, true);
$c_or_sc->super_column->columns = $this->array_to_columns($value, $timestamp);
$c_or_sc->super_column->timestamp = $timestamp;
}
else
{
$c_or_sc = new cassandra_ColumnOrSuperColumn();
$c_or_sc->column = new cassandra_Column();
$c_or_sc->column->name = $this->unparse_column_name($name, true);
$c_or_sc->column->value = $value;
$c_or_sc->column->timestamp = $timestamp;
}
$ret[] = $c_or_sc;
}
return $ret;
}
// Parse column names for Cassandra
function parse_column_name($column_name, $is_column=true)
{
if(!$column_name) return NULL;
return $column_name;
}
// Unparse column names for Cassandra
function unparse_column_name($column_name, $is_column=true)
{
if(!$column_name) return NULL;
return $column_name;
}
// Convert supercolumns or columns into an array
function supercolumns_or_columns_to_array($array)
{
$ret = null;
for ($i=0; $i<count($array); $i++)
foreach ($array[$i] as $object)
{
if ($object)
{
// If supercolumn
if (isset($object->columns))
{
$record = array();
for ($j=0; $j<count($object->columns); $j++)
{
$column = $object->columns[$j];
$record[$column->name] = $column->value;
}
$ret[$object->name] = $record;
}
// (Otherwise - not supercolumn)
else
{
$ret[$object->name] = $object->value;
}
}
}
return $ret;
}
// Get record from Cassandra
function get($table, $key, $super_column=NULL, $slice_start="", $slice_finish="")
{
try
{
$column_parent = new cassandra_ColumnParent();
$column_parent->column_family = $table;
$column_parent->super_column = $this->unparse_column_name($super_column, false);
$slice_range = new cassandra_SliceRange();
$slice_range->start = $slice_start;
$slice_range->finish = $slice_finish;
$predicate = new cassandra_SlicePredicate();
$predicate->slice_range = $slice_range;
$resp = $this->client->get_slice($this->keyspace, $key, $column_parent, $predicate, $this->consistency);
return $this->supercolumns_or_columns_to_array($resp);
}
catch (TException $tx)
{
$this->Debug($tx->why." ".$tx->getMessage());
return array();
}
}
// Convert array to columns
function array_to_columns($array, $timestamp=null) {
if(empty($timestamp)) $timestamp = time();
$ret = null;
foreach($array as $name => $value) {
$column = new cassandra_Column();
$column->name = $this->unparse_column_name($name, false);
$column->value = $value;
$column->timestamp = $timestamp;
$ret[] = $column;
}
return $ret;
}
// Get error string
function ErrorStr()
{
return $this->err_str;
}
}
// Initialize Cassandra
$cassandra = new CassandraDB("SPI");
// Debug on
$cassandra->SetDisplayErrors(true);
// Insert record ("Columns" in Cassandra)
$record = array();
$record["name"] = "Mike Peters";
$record["email"] = "mike at softwareprojects.com";
if ($cassandra->InsertRecord('mytable', "Mike Peters", $record)) {
echo "Record (Columns) inserted successfully.\r\n";
}
// Print record
$record = $cassandra->GetRecordByKey('mytable', "Mike Peters");
print_r($record);
?>
Any ideas on this, how to fix this?
Thanks a lot!
You really don't want to do Thrift by hand if you can avoid it. Take a look at phpcassa library:
https://github.com/thobbs/phpcassa
Oh, and in the above, looks like you want 'batch_mutate' not 'batch_insert' on ln. 75. That method changed names in versions of cassandra > 0.6.x

Categories