• Like
  • Save

Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Github.com anton terekhov-orientdb-php

  • 584 views
Published

 

Published in Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
584
On SlideShare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
0
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Signup and Pricing Explore Git Hub Feat ures Blog Loginvheren tnok To A P -Dn i O HB/e r Pt 28 3 Co de Ne t wo rk Pull Re que st s 0 Issue s 3 St at s & Graphs Binary protocol for OrientDB for PHP applications (Beta) — Read more ht t p://code.google.com/p/orient /wiki/Net workBinaryProt ocol Z IP HT T P G it R e ad - O nly https://github.com/AntonTerekhov/OrientDB-PHP.git R e ad - O nly access m ast e r Files Commits Branches 3 Tags 21 Downloads Latest commit to the mast e r branch Bumped to r4606 Ant o nTe re kho v autho red January 18 , 20 12 commit 07b69f4a45 OrientDB-PHP / name age message hist ory OrientDB January 17, 2012 Changed code to be compatible with protocol version 7 support. RECORD… [AntonTerekhov] SpeedTest November 29, 2011 New methods $record- >reset() for reset all record fields and $record- … [AntonTerekhov] Tests January 18, 2012 Test aligned with r4597 [AntonTerekhov] .gitignore April 19, 2011 Added .gitignore [AntonTerekhov] LICENSE April 19, 2011 License file word- wrapped [AntonTerekhov] example.php May 16, 2011 Huge addition on PHPDoc blocks [AntonTerekhov] PDFmyURL.com
  • 2. phpunit.xml November 29, 2011 Made PHPUnit verbose [AntonTerekhov]readme.markdown January 18, 2012 Bumped to r4606 [AntonTerekhov]speedtest.php May 16, 2011 Huge addition on PHPDoc blocks [AntonTerekhov]readme.markdownOrientDB-PHPA plain PHP driver to OrientDB graph database using its binary protocol.DescriptionCurrent status is: Beta.Code is licensed under New BSD License and provided "as is". For complete license inf ormation see f ile LICENSE .Current OrientDB version to work with is: 1.0rc8 (revision 4606). It can be downloaded f rom OrientDBs Downloads page.Code compatible to previous binary releases of OrientDB can be f ound in repositorys tags or in Downloads section.RequirementsT his library requires: PHP 5.3.x spl extension (since PHP 5.3.0 this extension is always available) PCRE extension (as of PHP 5.3.0 this extension cannot be disabled and is theref ore always present) bcmath extension (Since PHP 4.0.4, libbcmath is bundled with PHP. T hese f unctions are only available if PHP was conf igured with --enable-bcmath .). Used on 32bit systems f or dealing with 64bit long. PDFmyURL.com
  • 3. If PHP 5.3.x is a concern, you can try to run this code in version 5.2.x, however, this is not supported.Installing OrientDB-PHPMain public repository of OrientDB-PHP is hosted at https://github.com/AntonTerekhov/OrientDB-PHP.To install most recent version of library, just type git clone git://github.com/AntonTerekhov/OrientDB-PHP.gitwhere you want its f ile to be located.You can also want to get latest stable version, so check out Downloads section. Stables are marked with tags including this libraryversion and OrientDB version.Using OrientDB-PHPOrientDB-PHP uses autoload f unctionality, so you only need to include OrientDB.php f ile. require OrientDB/OrientDB.php;For a complex usage example see f ile example.php .Testing OrientDB-PHPOrientDB-PHP is covered with automatic tests by phpUnit. Tests are located in Tests/ directory.You can always re-test the whole library by typing phpunit Tests/Function list PDFmyURL.com
  • 4. Some f unctions requires to be already connected to OrientDB server (using connect() ) or to have database opened (using DBOpen() ). T his can be ref erenced at protocol description. If sequence is wrong - exception OrientDBWrongCommandException willbe thrown and no interaction with server will be made.Create a new instance of OrientDB class $db = new OrientDB(string $host, int $port[, int $connectTimeout]);Example: $db = new OrientDB(localhost, 2424);Connect to serverConnects to OrientDB server (not database) with user and password specif ied. Returns true on success or throws exception. bool $db->connect(string $userName, string $password);Example: $connected = $db->connect(root, passwd);Database f unctionsDBOpenOpen database f or work with or throws exception on f ailure (non-existent DB, wrong login or password). Return array consist ofcluster inf ormation and conf ig. array $db->DBOpen(string $dbName, string $userName, string $password);Example: PDFmyURL.com
  • 5. $config = $db->DBOpen(demo, writer, writer);DBCloseCloses currently opened database.Silently closes currently opened database, if any. Socket to OrientDB server is closed, and no f urther commands are possible. Willthrow an exception if no database are open on OrientDB instance. void $db->DBClose();DBCreat eCreates new database. Return true on success or throw an exception. bool $db->DBCreate(string $dbName, string $dbType);Available types is: OrientDB::DB_TYPE_MEMORY f or in memory database OrientDB::DB_TYPE_LOCAL f or physical databaseFor dif f erence see of f icial OrientDB docs.Example: $isCreated = $db->DBCreate(mydb, OrientDB::DB_TYPE_LOCAL);DBDelet eDelete database with name provided. Always return true . bool $db->DBDelete(string $dbName); PDFmyURL.com
  • 6. Example: $result = $db->DBDelete(testdb);DBExist sChecks if database with name provided is exists. Return true on success, false is no database exists or throws an exception. bool $db->DBExists(string $dbName);Example: $isExists = $db->DBExists(demo);Record manipulation f unctionsrecordCreat eCreate record in specif ied cluster with content and type. Returns record position in cluster. int $db->recordCreate( int $clusterID, string|OrientDBRecord $recordContent[, string $recordType]);Available record types are: OrientDB::RECORD_TYPE_BYTES OrientDB::RECORD_TYPE_DOCUMENT OrientDB::RECORD_TYPE_FLATDef ault type used is OrientDB::RECORD_TYPE_DOCUMENT .Example 1: PDFmyURL.com
  • 7. $recordPos = $db->recordCreate(1, name:"John");You can, however, use instance of class OrientDBRecord to create new entry in OrientDB server. If so, some of this instanceproperties ( clusterID , recordPos , recordID , version ) will be f illed with correct values. See example below:Example 2: $record = new OrientDBRecord(); $record->data->name = John; $recordPos = $db->recordCreate(1, $record); echo $record->recordPos . PHP_EOL; echo $record->clusterID . PHP_EOL; echo $record->recordID . PHP_EOL; echo $record->version . PHP_EOL;Can produce something like: 1 5 1:5 0Due to PHPs behavior, objects are always passed by ref erence instead of int, f or example. T his, if automatically updating ofrecord f ields is not an option, can get you in trouble. So, in that case you should see example below:Example 3: $record = new OrientDBRecord(); $record->data->name = John; $recordPos = $db->recordCreate(1, (string) $record);Please, note, that using OrientDBRecord instance doesnt automatically f ill up other f unction parameters. PDFmyURL.com
  • 8. recordDelet eDelete record with specif ied recordID and optionally, version. Returns true on success, false otherwise or throws anexception. bool $db->recordDelete(string $recordID[, int $recordVersion]);Def ault version is -1 . T his means no version check will be done.Example: $result = $db->recordDelete(1:1); $result = $db->recordDelete(1:1, 1);recordLoadLoad record by recordID and, optionally, f etchplan. Returns record or false . In some cases (e.g. recordPos is out of f ile bounds)can throw an exception OrientDBRecord $db->recordLoad(string $recordID[, string $fetchPlan]);Def ault f etchplan is *:0 , which mean load only record specif ied.Example: $record = $db->recordLoad(1:1);If f etchplan is explicit and there are some records returned by OrientDB, they located in $db->cachedRecords as associative arraywith keys f rom recordIDs and values are record themselves.T his example PDFmyURL.com
  • 9. $record = $db->recordLoad(1:1, *:-1); var_dump($db->cachedRecords);Will produce something like this: array(2) { ["11:0"]=> object(OrientDBRecord)#178 (8) { ...During next call to any method which is able to populate $db->cachedRecords (e.g. recordLoad() or command() ) this array willbe reset.recordUpdat eUpdate record with specif ied recordID and, optionally, version. Returns new record version on success, -1 otherwise or throws anexception. int $db->recordUpdate(string $recordID, string|OrientDBRecord $recordContent[, int $recordVersion[, string $recordType]]);Def ault version is -1 . T his means no version check will be done.Available record types are: OrientDB::RECORD_TYPE_BYTES OrientDB::RECORD_TYPE_DOCUMENT OrientDB::RECORD_TYPE_FLATDef ault type used is OrientDB::RECORD_TYPE_DOCUMENT .Examples 1: $version = $db->recordUpdate(1:1, Name:"Bob"); PDFmyURL.com
  • 10. $version = $db->recordUpdate(1:1, Name:"Sam", 1, OrientDB::RECORD_TYPE_DOCUMENT);You can, however, use instance of class OrientDBRecord to update record in OrientDB server. If so, some of this instanceproperties ( clusterID , recordPos , recordID , version ) will be f illed with correct values. See example below:Example 2: $record = new OrientDBRecord(); $record->data->name = John; $recordPos = $db->recordUpdate(1:1, $record); echo $record->recordPos . PHP_EOL; echo $record->clusterID . PHP_EOL; echo $record->recordID . PHP_EOL; echo $record->version . PHP_EOL;Can produce something like: 1 1 1:1 3Due to PHPs behavior, objects are always passed by ref erence instead of int, f or example. T his, if automatically updating ofrecord f ields is not an option, can get you in trouble. So, in that case you should see example below:Example 3: $record = new OrientDBRecord(); $record->data->name = John; $recordPos = $db->recordUpdate(1:1, (string) $record);Please, note, that using OrientDBRecord instance doesnt automatically f ill up other f unction parameters. PDFmyURL.com
  • 11. Conf ig commandsconf igListGet list of conf igurable options. Returns associative array with keys f rom option names and values themselves. array $db->configList();Example: $options = $db->configList();conf igGetGet value f or conf ig option. Returns value as string . If option name not f ound returns empty string . string $db->configGet(string $optionName);Example: $value = $db->configGet(log.console.level);conf igSetSet value f or conf ig option. Returns true on success or throws an exception. bool $db->configSet(string $optionName, string $optionValue);Example: $result = $db->configSet(log.console.level, info); PDFmyURL.com
  • 12. Datacluster commandsdat aclust erAddAdd new datacluster with specif ied name and type. Returns new cluster ID or throws an exception. int $db->dataclusterAdd(string $clusterName, string $clusterType);Cluster types available are: OrientDB::DATACLUSTER_TYPE_LOGICAL OrientDB::DATACLUSTER_TYPE_PHYSICAL OrientDB::DATACLUSTER_TYPE_MEMORYExample: $clusterID = $db->dataclusterAdd(testcluster, OrientDB::DATACLUSTER_TYPE_PHYSICAL);dat aclust erRemoveRemoves datacluster by its ID. Returns true on success or throws an exception. bool $db->dataclusterRemove(int $clusterID);Example: $result = $db->dataclusterRemove(10);dat aclust erCountCounts elements in clusters specif ied by cluster IDs. Returns count or throws an exception. int $db->dataclusterCount(array $clusterIDs); PDFmyURL.com
  • 13. Example: $count = $db->dataclusterCount(array(1, 2));dat aclust erDat arangeReturns datarange f or specif ied cluster ID. Returns array of start and end positions or throws an exception. array $db->dataclusterDatarange(int $clusterID);Example: $data = $db->dataclusterDatarange(int $clusterID); array(2) { ["start"]=> int(0) ["end"]=> int(126) }commitCommits a transaction. Not yet implemented.countGet count of records in cluster specif ied by clusterName. Returns int or throws an exception. int $db->count(string $clusterName);Example: PDFmyURL.com
  • 14. $newcount = $db->count(default);Querying servercommandT his command provide an ability to execute remote SQL commands . Returns mixed or throws an exception. mixed $db->command(int $commandMode, string $query[, string $fetchplan]);Command mode is required to be properly match with query text.Command modes available are: OrientDB::COMMAND_QUERY - f or general queries, including INSERT , UPDATE , DELETE , FIND REFERENCES , etc. OrientDB::COMMAND_SELECT_SYNC - only f or SELECT in synchronous mode OrientDB::COMMAND_SELECT_ASYNC - only f or SELECT in asynchronous modeFetchplan is used to pre-f etch some records. Fetchplan is only available in OrientDB::COMMAND_SELECT_ASYNC mode. Usingf etchplan will populate $db->cachedRecords array as f or recordLoad() .Def ault f etchplan is *:0 .Examples: $records = $db->command(OrientDB::COMMAND_SELECT_ASYNC, select * from city limit 7); $records = $db->command(OrientDB::COMMAND_SELECT_ASYNC, select from city traverse( any() ), *:-1); $false = $db->command(OrientDB::COMMAND_SELECT_SYNC, select from 11:4 where any() traverse(0,10) (address.city = "Rome")); $links = $db->command(OrientDB::COMMAND_QUERY, find references 14:1); $record = $db->command(OrientDB::COMMAND_QUERY, insert into city (name, country) values ("Potenza", #14:1)); $updatedCount = $db->command(OrientDB::COMMAND_QUERY, update city set name = "Taranto" where name = "Potenza"); $deletedCount = $this->db->command(OrientDB::COMMAND_QUERY, delete from city where name = "Taranto"); PDFmyURL.com
  • 15. selectIs an alias f or command(OrientDB::COMMAND_SELECT _SYNC, string $query). mixed $db->select(string $query);Example: $records = $db->select(select from city traverse( any() ));selectAsyncIs an alias f or command(OrientDB::COMMAND_SELECT _ASYNC, string $query[, string $f etchplan]). mixed $db->selectAsync(string $query[, string $fetchplan]);Example: $records = $db->selectAsync(select * from city limit 7, *:-1);queryIs an alias f or command(OrientDB::COMMAND_QUERY, string $query). mixed $db->query(string $query);Example: $records = $db->query(insert into city (name, country) values ("Potenza", #14:1) );shutdown PDFmyURL.com
  • 16. Remotely shutdown OrientDB server. Require valid user name and password. See manual f or details. Returns nothing on successor throws an exception. void $db->shutdown(string $userName, string $password);Example: $db->shutdown(root, password);Exceptions listFor present moment OrientDB-PHP is using this list of exceptions: OrientDBException - base exception, all exceptions listed below are extending this class. T his class used as general error class (in case of OrientDB problems). OrientDBConnectException - thrown on connect errors. OrientDBDeSerializeException - thrown on de-serialization errors. OrientDBWrongCommandException - wrong command sequence exception, f or example thrown on call recordLoad() if DB is not opened yet. OrientDBWrongParamsException - wrong params count or other param-related issues.OrientDBRecordT his class is representing OrientDB record.Class is holding as much inf ormation f rom OrientDB as we received.Class f ieldsClass f ields are: className - Class name f rom OrientDB. PDFmyURL.com
  • 17. type - Document type f rom OrientDB. E.g. OrientDB::RECORD_TYPE_DOCUMENT . clusterID - Cluster ID, f rom which record was loaded. recordPos - Record position in cluster. recordID - Fully qualif ied record ID in f ormat clusterID:recordPos . version - Document version f rom OrientDB. content - Document content as string in OrientDBs representation. data - placeholder where data, deserialized f rom content , is stored. Developer should manipulate this data in applications.For complete inf ormation on f ields data types see PHPDoc in class.At this point some class fields are public. Please, be careful.However, class f ields content , clusterID , recordPos , recordID and className are using magic methods. All of them areavailable f or reading, while f ields clusterID , recordPos and className only f or writing.Class methodsClass methods are: parse() - can be called af ter maximum amount of f ields was populated. Parses content and f ill up f ields data and className . Field recordPos are f illed up automatically on setting recordID or clusterID via magic method __set() . In general, there is no need to call this method directly f rom user code, as record content is parsed automatically on request to any data or className f ields. T his is done via OrientDBRecordData class. T his magic parsing only done once, until new content is assigned. setParsed() - f orces that record was already parsed. __toString() - serialize back all f ields f rom data . Return a string. Also can be called implicitly as type casting, e.g. (string) $record . reset() - f ully reset class f ields, equals to new resetData() - will reset class data, except f or clusterID and className . PDFmyURL.com
  • 18. Class is able to parse almost any record f ormat as received f rom OrientDB server. However, there are some limitations about f ewJava primitive data types, e.g. short. T his is a planned T ODO.ExamplesrecordLoad: $record = $db->recordLoad(12:1, *:2); var_dump($record);will produce object(OrientDBRecord)#197 (9) { ["className"]=> string(7) "Address" ["type"]=> string(1) "d" ["clusterID"]=> int(12) ["recordPos"]=> int(1) ["recordID"]=> string(4) "12:1" ["version"]=> int(0) ["content"]=> string(61) "Address@street:"Piazza Navona, 1",type:"Residence",city:#13:0" ["data"]=> object(stdClass)#172 (3) { ["street"]=> string(16) "Piazza Navona, 1" ["type"]=> string(9) "Residence" ["city"]=> object(OrientDBTypeLink)#195 (1) { ["link":"OrientDBTypeLink":private]=> PDFmyURL.com
  • 19. ["link":"OrientDBTypeLink":private]=> string(4) "13:0" } } }recordCreate $record = new OrientDBRecord(); $record->data->FirstName = Bruce; $record->data->LastName = Wayne; $record->data->appearance = 1939; $recordPos = $db->recordCreate($clusterID, (string) $record); var_dump($db->recordLoad($clusterID . : . $recordPos));will produce object(OrientDBRecord)#176 (9) { ["className"]=> NULL ["type"]=> string(1) "d" ["clusterID"]=> int(1) ["recordPos"]=> int(138) ["recordID"]=> string(5) "1:138" ["version"]=> int(0) ["content"]=> string(50) "FirstName:"Bruce",LastName:"Wayne",appearance:1939" ["data"]=> object(stdClass)#179 (3) { ["FirstName"]=> string(5) "Bruce" PDFmyURL.com
  • 20. ["LastName"]=> string(5) "Wayne" ["appearance"]=> int(1939) } }DatatypesDue to small quantity of PHPs built-in datatypes, this library is introducing some own datatypes.OrientDBLinkUsed to link records with each other.Two variants of constructing new instance is available: OrientDBTypeLink(string $value);String value can be def ined with or without leading hash sign. OrientDBTypeLink(int $clusterID, int $recordPos);Example 1: String with hash sign $link = new OrientDBTypeLink(#100:99); echo $link . PHP_EOL; echo $link->getHash() . PHP_EOL; echo $link->get() . PHP_EOL; echo $link->clusterID . PHP_EOL; echo $link->recordPos . PHP_EOL;Example 2: String without hash sign PDFmyURL.com
  • 21. $link2 = new OrientDBTypeLink(100:99); echo $link2 . PHP_EOL; echo $link2->getHash() . PHP_EOL; echo $link2->get() . PHP_EOL; echo $link->clusterID . PHP_EOL; echo $link->recordPos . PHP_EOL;Example 3: Two integers $link3 = new OrientDBTypeLink(100, 99); echo $link2 . PHP_EOL; echo $link2->getHash() . PHP_EOL; echo $link2->get() . PHP_EOL; echo $link->clusterID . PHP_EOL; echo $link->recordPos . PHP_EOL;Output of all these examples would be the same: #100:99 #100:99 100:99 100 99OrientDBTypeTimeUsed to store OrientDB date f ormat with timestamps. OrientDBTypeLink(mixed $value);Example: $date = new OrientDBTypeDate(1302631023t); $date2 = new OrientDBTypeDate(1302631023); PDFmyURL.com
  • 22. echo (string) $date . PHP_EOL; echo $date->getValue() . PHP_EOL; echo $date->getTime() . PHP_EOL;Both $date and $date2 will output the same: 1302631023t 1302631023t 1302631023Debugging with OrientDB-PHPFor debug purposes you can enable or disable debug output at anytime.Example: $db->DBOpen(demo, writer, writer); $recordPos = $db->recordCreate($clusterID, $recordContent); $this->db->setDebug(true); $record = $db->recordLoad($clusterID . : . $recordPos); $this->db->setDebug(false); $result = $db->recordDelete($clusterID . : . $recordPos);T he above example will output debug messages only f or recordLoad() to standard output stream (browser or console) in thismanner: 0 : 1e 00 00 00 04 00 01 00 00 00 00 00 00 00 8f 00 [................] 10 : 00 00 03 2a 3a 30 [...*:0] >request_status 0 : 00 [.] >TransactionID 0 : 00 00 00 04 [....] >record_status_first PDFmyURL.com
  • 23. 0 : 01 [.] >record_content 0 : 00 00 00 0c [....] 0 : 74 65 73 74 72 65 63 6f 72 64 3a 30 [testrecord:0] >record_version 0 : 00 00 00 00 [....] >record_type 0 : 64 [d] >record_status_cache 0 : 00 [.]Planned TODOs Full support on Java primitive data types, e.g. short or byte. Possible more OOP-style work with OrientDBRecord. Possible using libevent f or selectAsync(). Support f or async mode f or RECORD_CREAT E, RECORD_UPDAT E, RECORD_DELET E Support f or converting string true to actual boolean true (and other values) in SQLKnown bugs Connecting to OrientDB instance, which is listening 0.0.0.0 (def ault f or OrientDB) can cause errors. Change to 127.0.0.1 in Orients conf iguration. See issueIf you found a bugIf you f ound a bug - f eel f ree to contact me via gitHub, email, or open a new issue. PDFmyURL.com
  • 24. Git Hub To o ls Ext ras Do cum e nt at io nAbo ut Gauges: Analyze web traffic GitHub Sho p GitHub HelpBlo g Speaker Deck: Presentatio ns The Octo dex Develo per APIFeatures Gist: Co de snippets GitHub Flavo red Markdo wnCo ntact & Suppo rt GitHub fo r Mac GitHub PagesTraining Issues fo r iPho neGitHub Enterprise Jo b Bo ardSite StatusTerms o f Service Privacy Security Po wered by the Dedicated Servers and© 20 12 GitHub Inc. All rights reserved. Clo ud Co mputing o f Rackspace Ho sting ® PDFmyURL.com