Skip to content

Example Calls

Adam Anderly edited this page Feb 15, 2017 · 21 revisions

Usage Examples

Initialize the OData Client

    use SaintSystems\OData;

    // Using the example OData service from odata.org
    $odataServiceUrl = 'http://services.odata.org/V4/TripPinService';
    $odataClient = new ODataClient($odataServiceUrl);

Initialize the OData Client with an Authentication Delegate

    use SaintSystems\OData;

    // Need to authenticate the requests to the service? 
    // Pass in an Authentication Delegate Closure as the second argument
    // which will get passed the request object. The Closure will be
    // called prior to every request.

    // Access token retrieved from an oauth provider
    $accessToken = 'abc';
    $odataClient = new ODataClient($odataServiceUrl, function($request) {
        // OAuth Bearer Token Authentication
        $request->headers['Authorization'] = 'Bearer '.$accessToken;
        // OR Basic Authentication
        $username = 'foo';
        $password = 'bar';
        $request->headers['Authorization'] = 'Basic '.base64_encode($username.':'.$password);
    });

Get a collection of items

    // Retrieve all entities from the "People" Entity Set
    // Issues a GET HTTP request to http://services.odata.org/V4/TripPinService/People
    $people = $odataClient->from('People')->get();

Get a specific item from a collection by ID

    // Or retrieve a specific entity by the Entity ID/Key
    // Issues a GET HTTP request to http://services.odata.org/V4/TripPinService/People('russellwhyte')
    $person = $odataClient->from('People')->find('russellwhyte');
    echo "Hello, I am $person->FirstName ";

Get only certain properties/columns from a collection

    // Select only the "FirstName" and "LastName" properties
    // Issues a GET HTTP request to http://services.odata.org/V4/TripPinService/People?$select=FirstName,LastName
    $people = $odataClient->from('People')->select('FirstName','LastName')->get();

Filter a collection

    // Select only records whose FirstName = "Russell"
    // Issues a GET HTTP request to http://services.odata.org/V4/TripPinService/People?$filter=FirstName eq 'Russell'
    $people = $odataClient->from('People')->where('FirstName','=','Russell')->get();

    // Omitting the "=" operator defaults to "=" operator (synonymous with the request above)
    $people = $odataClient->from('People')->where('FirstName','Russell')->get();
Clone this wiki locally