Overview arrow_sm.gif Architecture arrow_sm.gif Installation Guide arrow_sm.gif User Guide arrow_sm.gif FAQ arrow_sm.gif Contributors

User Guide

Introduction

Toolkit for PHP with ADO.NET Data Services is designed to make it easier for PHP applications to consume data services created using the ADO .NET Data Services framework. The goal is to provide the same functionality that is available in the libraries available to .NET developers. The library includes support for accessing and modifying the data exposed by the ADO .NET Data Service.

Requirements

This toolkit requires the following frameworks to be installed and enabled
PHP XSL Extension
PHP CURL Extension

Package Content

\Doc:
  • Toolkit User guide
\Samples\ADODotNETDataServices:

A Visual Studio 2008 project for two sample ADO .NET Data Services used by the sample applications included in the PHP Toolkit. The Visual Studio project creates two services:
  • NorthWindDataService: This service is used by the SimpleApplications and can be used to test the ADODotNETDataServicesEditor
  • GameStoreDataService: service used by the Game Store sample Application.
\Sample\PHPApplications:
  • ADODotNETDataServicesEditor: a PHP application that can be used to connect, browse, read and write data exposed by an ADO .NET Data Service.
  • SimpleApplications: a list of simple HelloWorld-type applications that show how ADO .NET Data Services queries can be used to retrieve data from a server.
  • VideoGameStoreApplication: a sample application that shows how ADO .NET Data Services can be used to access a remote data source.
\framework:
  • Contains the source code for the tools used to generate the proxy class and to communicate with data service.

Installation and Configuration

The assumption is that PHP is already installed and configured on the machine where the ADO .NET Data Services toolkit is installed.
The toolkit does not have any dependency on the host OS so it can run on Windows, Linux or Mac OSX machines.
  • Create a folder named 'adodotnetservicesphp' eg: C:\PHPLib\adodotnetservicesphp
  • Copy the following files to the folder created above.
    • ADODotNETDataServices2PHPProxy.xsl
    • ADODotNETDataServicesEditor.php
    • ADODotNETDataServicesEntity.php
    • ADODotNETDataServicesException.php
    • PHPDataSvcUtil.php
    • HttpProxy.php
    • Common (contains Dictionary.php, Guid.php and Utility.php)
    • Context (contains EntityStates.php, ObjectContext.php, QueryProcessor.php, RelatedEnd.php, ResourceBox.php and SaveResult.php)
    • Credential (contains Credentail.php)
    • Interfaces (contains Entity.php and Object.php)
    • Parser (contains Parser.php, AtomParser.php and JSONParser.php)
    • Resource (contains Messages.php)
    • WebUtil (contains HttpBatchRequest.php, HttpBatchResponse.php, HttpRequest.php , HttpResponse.php and MicrosoftHttpResponse.php)
  • Add the path to the folder created in step 1 to the 'include_path' directive in php.ini. e.g.
   include_path = ".;C:\PHPLib\adodotnetservicesphp" 

  • Create a variable called 'adodotnetservicesphp_path' in the php.ini file and set it to the path where the PHP Toolkit was installed (step 1). Open php.ini and search for 'Paths and Directories' section. Just below the definition of 'include_path' directive, add the following two lines:
   ;Toolkit for PHP with ADO.NET Data Services Library Path
   adodotnetservicesphp_path = "C:\PHPLib\adodotnetservicesphp"          

  • On linux platform, make sure you have the php-xml module installed. This can be installed using yum as follows,
   yum install php-xml

  • Enable php_xsl.dll in php.ini. Search for 'extension=php_xsl.dll' in the php.ini file and remove the semicolon (;) in front.
  • Enable php_curl.dll in php.ini. Search for 'extension=php_curl.dll' in the php.ini file and remove the semicolon (;) in front.
  • Optional: The content of the PHPApplications directory can be deployed on a web server to provide access to the sample applications from a single web page. The PHPApplications directory contains some php files, template and CSS files that are used to build the Sample Web Page. All Samples must be configured before they can be ran from the Web Page. Refer to the readme files in the ADODotNETDataServiceEditor, SimpleApplications and GameStoreApplication directories.

Creating Proxy Class

The first step is to create a proxy class that is used to connect to the ADO .NET Data service.
The PHP client library provides a PHPDataSvcUtil.php file which creates the proxy class. The command to create the class is
php <path of Client Libary>PHPDataSvcUtil.php /Uri:<data service Uri> [/metadata:<path to metadata file> [/out:<output file path>] 

<Path of Toolkit Library> is the path where the toolkit library files are installed (See the installation instructions).
If file name is not specified with the /Out parameters, the Entity Container name (defined in the ADO .NET Data Service) is used as filename. If the output path is not specified then the proxy class will be generated by PHPDataSvcUtil in the current directory.
The metadata param can be used to specify a medata file saved on the local machine. The PHPDataSvcUtil will use the saved file and won’t connect to ADO .NET Data Service. Uri and metadata params are mutually exclusive.
Note: In order to use this utility, the configuration option {'adodotnetservicesphp_path'} should be set in php.ini configuration file. (Refer Installation and Configuration section for more details).

Using Proxy Class

After the proxy class for the ADO .NET Data Service has been created, it can be used in the application to access the data on the server. The proxy class generated by the PHPDataSvcUtil needs to be included first:
require_once 'MyProxyClass.php';

The MyProxyClass.php file, in this case, contains the definition of a class that can be use to execute various queries using the ExecuteQuery method.
The following code snippet shows an example on how to use the proxy class to access a customer record for a service that exposes the NorthWind database.
The goal is to retrieve the record for the Costumer with CustomerID=’ALFKI’
$proxy = new NorthwindEntities();
$customers = $proxy->ExecuteQuery(“Customers(‘ALFKI’)”);
echo ($customers-CompanyName);

This code sample uses the proxy class to connect to the ADO .NET Data Service, retrieves a customer and prints the CompanyName field using the customers class defined in the myproxyclass.php file.

Data Service Queries

The data service queries are conditions that determine what data is retrieved from the ADO .NET Data Service. There are five Data Service Queries supported by the Toolkit for PHP with ADO.NET Data Services.
  • Expand
  • Filter
  • OrderBy
  • Skip
  • Top
Complete documentation on the Data Service Queries can be found on the MSDN site

Expand Query

The ‘expand’ option allows you to embed one or more sets of related entities in the results. For example, if you want to display a customer and its sales orders, you could execute two requests, one for Customers(‘ALFKI’) and one for Customers(‘ALFKI’)Orders. The ‘expand’ option on the other hand allows you to return the related entities in-line with the response of the parent in a single HTTP request.
You may specify multiple navigation properties to expand by separating them with commas, and you may traverse more than one relationship by using a dot to jump to the next navigation property.
Examples:
// a customer with related sales orders 
$customers = $proxy->ExecuteQuery(“Customers(‘ALFKI’)?\$expand=Orders);
echo count($customers-Orders);

// a customer with related sales orders and employee information related to those orders 
$customers = $proxy-ExecuteQuery(“Customers(‘ALFKI’)?\$expand=Orders/Employees); 
echo count($customers->Orders(10248)->Employees);

 //Orders with related employees information and related shipper information 
$customers = $proxy->ExecuteQuery(“Orders(10248)\$expand=Employees,Shippers);
echo count($customers->Employees(5)->Shippers);
echo count($customers->Employees);

Note “$” is a special key in PHP, therefore “\” is added before “$” in the query.

Filter Query

Restrict the entities returned from a query by applying the expression specified in this operator to the entity set identified by the last segment of the URI path.
For example
 //all customers in London 
$customers = $proxy-ExecuteQuery(“Customers?\$filter=City eq ‘London’);

 //Match all Customers with the value of the property ‘fullname’ equal to ‘Wayne, John’ 
$customers = $proxy-ExecuteQuery(“Customers?\$filter='Wayne, John' eq insert(ContactName, length(lastname), ','));

Conditions that can be used in the filter condition are

Condition Description
Eq Equals
Ne Not equals
Lt Less than
Le Less than or equal
Gt Greater than
Ge Greater than or equal

Order By Query

Sort the results by the criteria given in this value. Multiple properties can be indicated by separating them with a comma. The sort order can be controlled by using the “asc” (default) and “desc” modifiers.
For example
$customers = $proxy->ExecuteQuery(“Customers?\$orderby=City);
$customers = $proxy->ExecuteQuery(“Customers?\$orderby=City desc);
$customers = $proxy->ExecuteQuery(“Customers?\$orderby=City desc,CompanyName asc);

Skip Query

Skip the number of rows given in this parameter when returning results. This is useful in combination with “top” to implement paging (e.g. if using 10-entity pages, saying $skip=30&top=$10 would return the fourth page).
NOTE: Skip only makes sense on sorted sets; if an orderby option is included, ‘skip’ will skip entities in the order given by that option. If no orderby option is given, ‘skip’ will sort the entities by primary key and then perform the skip operation.
For example:
 //return all customers except the first 10 
$customers = $proxy->ExecuteQuery(“Customers?\$skip=10);

 //return the 4th page, in 10-row pages 
$customers = $proxy->ExecuteQuery(“Customers?\$skip=30&\top=10);

Top Query

Restrict the maximum number of entities to be returned. This option is useful both by itself and in combination with skip, where it can be used to implement paging as discussed in the description of ‘skip’.
 //top 5 sales orders 
$customers = $proxy-ExecuteQuery(“Customers?\$top=5);

 //top 5 sales orders with the highest TotalDue 
$customers = $proxy-ExecuteQuery(“Orders?\$orderby=TotalDue&\$top=5);

Creating new instance in data service

In this scenario a new object is created on the client and then made persistent by saving it on the database exposed by the ADO .NET Data Service.
To create a new instance in the data service, first a new php object needs to be created and the required properties populated, then by calling AddObject and passing the object and the target entity-set, the object is added to the collection of objects in the database. A final call to the SaveChanges method makes the actual call that will save the new object in the database. The Following code snippet shows how to use this functionality.
require_once 'MyProxyClass.php'; 

$proxy = new NorthwindEntities(); 

//Create a Customers php Object  

$customer = Customers::CreateCustomers("CHAN9", "channel9"); 

//inserting Customers object context tracking system  

$proxy->AddObject(‘Customers’, $customer); 

//SaveChange insert the object into data service 

$proxy->SaveChanges();
 

Updating an existing instance in data service

To update an existing instance in the data service, first an instance from data service needs to be retrieved using the ExecuteQuery or LoadProperty methods. After the object has been retrieved and the properties set with the new values a call to the UpdateObject applies the changes to the table(s) in the database. The following code snippet shows how to use UpdateObject API.
require_once 'MyProxyClass.php'; 

$proxy = new NorthwindEntities(); 
$customers = $proxy->ExecuteQuery(“Customers(‘CHAN9’)); 

//update the CompanyName property 

$customer->CompanyName = "Channel8"; 

//add the object to the list of objects that needs to be updated in the database 

$proxy->UpdateObject($customer); 

//SaveChanges updates the object in the data service 

$proxy->SaveChanges();
 

Deleting an existing instance from data service

Similar to the Update scenario, to delete an existing instance in the data service, first an instance needs to be retrieved using ExecuteQuery or LoadProperty methods, then a call to the DeleteObject methods adds the objects to the list of objects that needs to be deleted in the database. . The following code snippet shows how to use DeleteObject API.
require_once 'MyProxyClass.php'; 

$proxy = new NorthwindEntities(); 

//Get the object by calling the ExecuteQuery Method
 
$customers = $proxy->ExecuteQuery(“Customers(‘CHAN9)); 

//The object is added to the list of objects to delete in the database 

$proxy->DeleteObject($customer); 

//SaveChanges makes the actual changes in the database  

$proxy->SaveChanges(); 
 

Creating link between instances

If you have a relationship between two entities in the data service, then you can use AddLink to create relationship between the corresponding entity instances. The following code snippet shows how to create link between a Customers instance and Orders instances.
require_once 'MyProxyClass.php'; 

$proxy = new NorthwindEntities(); 

//Create a Customers instance  

$customer = new Customers(); 
$customer ->CustomerID = 'CHAN9'; 
$customer ->CompanyName = 'channel9'; 
$proxy->AddToCustomers($customer); 

//Create an Orders instance 

$Order = new Orders(); 

//Create link between Customer and Order. 

$proxy->AddLink($cust, "Orders", $ Order); 
$proxy->SaveChanges(); 
 

Deleting link between instances

If you have two related entity instances in data service, then you can use DeleteLink to remove the relationship between these two. The following code snippet shows how to delete the link.
require_once 'MyProxyClass.php'; 

$proxy = new NorthwindEntities(); 

//Retrive the Customers entity with key ‘CHAN9’  

$query = $proxy->ExecuteQuery("Customers(CustomerID='CHAN9')") 
foreach($query as $customer) 
{ 
//Load the Orders property 

$proxy->LoadProperty($customer, "Orders") ; 
foreach($customer->Orders as $o) 
{ 
$proxy->DeleteLink($customer, "Orders", $o); 
} 
} 

$proxy->SaveChanges(); 
 

Authentication in the Client Library

This toolkit also handles authentication. By default, the client library assumes the ADO .NET Data Service uses an anonymous connection so user credentials don't need to be specified.. However, you can set the Credentials property in the proxy object to point to an object holding the credential information. The Credential property will be used if the ADO .NET Data Service requires the user to be authenticated.
$proxy->Credential = new Credential(user-name, password); 
 

Custom authentication Support

In more advanced scenario, the client application might need to set custom headers; the toolkit exposed the addHeader method for that. To remove the custom headers which are added call RemoveHeaders. The following code snippet shows how to use this functionality.
$proxy->AddHeader(custom-header-name, custom-header-value); 
$proxy->RemoveHeaders(); 
 

Connecting to Data Service through proxy server

If connecting to data service requires proxy server, you can set the Proxy property in the Httpproxy object to point to an object holding the proxy server information.
$proxy->HttpProxy = new HttpProxy(proxy-server-name, proxy-server-port);  
 

Sample Applications

Sample Application included in the toolkit can be found under the SamplesPHPApplications.

Simple Demo and ADO .NET Data Services Editor Applications

Simple Demo and ADO .NET Data Services Editor applications use the NorthWindDataService service that can be built with the Visual Studio project under the \Samples\ADODotNETDataServices directory. If you changed any of the default settings in the Visual Studio project, you will have to regenerate the proxy class (NorthWindEntities.php) before you can run the sample application.

Game Store Application

The Game Store sample application uses the GameStoreDataService that can be built using the Visual Studio project under the \Samples\ADODotNETDataServices directory. If you changed any of the default settings in the Visual Studio project, you will have to regenerate the proxy class (VideoGameStoreEntities.php) before you can run the sample application.

Reference Section

List of APIs supported by PHP Client Library.
API Prototype Parameters Return Value Description
ExecuteQuery(query-expression) The query to be executed against data service. Please refer ‘Data Service Queries’ section for more details OnSuccess: Returns result of query as a collection. OnFailure: If any error occurs (ex: malformed query), then client library will throw ADODotNETDataServicesException exception with proper message. To execute queries against the data service
AddObject(TargetEntitySet, Object) TargetEntitySet : The name of entity set to which Object belongs to. Object : PHP Object represents the instance of a data service entity to be inserted. OnSuccess: Returns 1 OnFailure: If any error occurs (ex: if entity instance already exists), then client library will throw ADODotNETDataServicesException exception with proper message To create a new instance in the data service
UpdateObject(Object) Object : PHP Object represents the existng instance of a data service entity, which is to be updated. OnSuccess: Returns 1 OnFailure: If any error occurs (ex: if entity instance not exists), then client library will throw ADODotNETDataServicesException exception with proper message. To modify an existing entity instance.
DeleteObject(Object) Object : PHP Object represents the existing instance of a data service entity, which is to be deleted. OnSuccess: Returns 1 OnFaliure: If any error occurs (ex: if entity instance not exists), then client library will throw ADODotNETDataServicesException exception with proper message. To delete an entity instance.
AddLink(Source, SourceProperty, Target) Source: The source object in the link. SourceProperty: The name of the property on the source object that represents the source in the link between the source and the target. Target: The target object involved in the link that is bound to the source object. OnSuccess: Returns 1 OnFailure: If any error occurs, then client library will throw ADODotNETDataServicesException exception with proper message. To add a link between two entity instances, assuming that there is a relationship between Two entities
DeleteLink(Source, SourceProperty, Target) Source: The source object in the link. SourceProperty: The name of the property on the source object that represents the source in the link between the source and the target. Target: The target object involved in the link that is bound to the source object. OnSuccess: Returns 1 OnFailure: If any error occurs, then client library will throw ADODotNETDataServicesException exception with proper message. To delete link between two entity instances.
AddHeader(Header-Name, Header-Value) Header-Name: The name of custom HTTP header Header-Value: The value of custom HTTP header. No return value. To add custom headers
RemoveHeaders() No argument No Return value To Remove all custom headers aded by user
SaveChanges() No arguments Thows ADODotNETDataServicesException exception with proper message if any of the command generated for changes fails. To save the changes made to the entities in the context to data service.

Last edited Sep 15, 2009 at 7:41 AM by anu_chandy, version 21

Comments

No comments yet.