incraigulous/contentful-sdk

1.0 2015-08-29 01:49 UTC

This package is auto-updated.

Last update: 2024-11-10 04:22:29 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License Daily Downloads Build Status

#DEPRECATED. Use Contentful's official PHP SDK.

Contentful SDK for PHP

A modern PHP SDK for Contentful delivery and management APIs.

###This is a framework agnostic PHP SDK.

####Looking for the Laravel Toolkit?

Click Here for Laravel facades, a base repository, out-of-the-box caching and cache management, webhook creation by command and more.

New to Contentful? Contentful is an API driven CMS. Check out their website and API documentation.

##Installation

Install via composer by running:

composer require "incraigulous/contentful-sdk:0.0.*"

##How to use it

###Content Delivery API

####Initializing

Create a new instance of the delivery SDK:

    use Incraigulous\ContentfulSDK\DeliverySDK;
    $deliverySDK = new DeliverySDK('TOKEN', 'SPACE_ID', $cacher);

Token: Your Contentful API token. You can generate this using the Contentful control panel.

Space ID: (optional) The space to use for calls made by the instance. To use multiple spaces, you should use multiple SDK instances. If you don't provide a space ID, you'll only be able to use the spaces resource.

Cacher: (optional, Incraigulous\ContentfulSDK\CacherInterface Implementation) An object to handle caching. This is optional (and easy to implement), so don't let it scare you off. Check out the caching section for more details.

####Spaces

#####Getting all spaces

$result = $deliverySDK->spaces()->get();

#####Getting a space

$result = $deliverySDK->spaces()
				->find('SPACE_ID')
				->get();

####Content Types

#####Getting a content type

$result = $deliverySDK->contentTypes()
				->find('CONTENT_TYPE_ID')
				->get();

#####Searching content types

$result = $deliverySDK->contentTypes()
				->where('name', '=', 'Blog Post')
				->get();

or

$result = $deliverySDK->contentTypes()
				->where('name', 'ne', 'Blog Post')
				->limit(2)
				->get();

See Search Parameters to learn how to search for specific things.

####Entries

#####Get an Entry by ID

$result = $deliverySDK->entries()
				->find('ENTRY ID')
				->get();

#####Searching for entries

$result = $deliverySDK->entries()
				->limitByType('CONTENT TYPE ID')
				->where('fields.title', 'match', 'campus')
				->where('fields.location', 'near', '22,23')
				->limit(10)
				->get();

######Including linked entries in search results

$result = $deliverySDK
	->where('sys.id', '=', 'ENTRY ID')
	->includeLinks(3)
	->get();

includeLinks takes the number of link levels you want to include.

####Assets

#####List all assets

$result = $deliverySDK->assets()
            	->limit(10)
            	->get();

#####Get an asset by ID

$deliverySDK->assets()
            	->find('ASSET ID')
            	->get();

#####Searching for assets

$result = $deliverySDK->assets()
              ->where('fields.file.details.size', '>=', 350000)
              ->limit(5)
              ->get();

####Search Parameters

Searching is easy! Just call one or more of the following methods on your resource. The use of where() and limit() on the assets resource as shown above is a great example of searching.

#####Where Filter Operators

For more detailed documentation on searching, see Contentful's API documentation.

#####Caching

I recommend you cache all Delivery API GET request results (i.e. Memcached or Redis). If you're working with a low traffic website you might be able to get by without caching, but it will greatly improve performance in any case.

One way would be to wrap all your API GET calls in a cache check, but that could lead to code duplication. Lucky for you, there's a better way.

I've included a cacher interface. Don't worry, it only requires four methods. Just build a class that implements Incraigulous\ContentfulSDK\CacherInterface and pass it as the third parameter when you instantiate the SDK. The SDK will handle the rest. Each GET request will be cached with a unique key built from the query using your cacher class.

	$cacher = new CustomCacher(); 
    $deliverySDK = new DeliverySDK('SPACE_ID', 'TOKEN', $cacher);

Here's an example using Laravel's Cache helper.

######If you build a generic PHP cacher implementation for Redis or Memcached, submit a pull request. I would love to include it in the repo.

###Management API

####Initializing

Create a new instance of the management SDK:

    use Incraigulous\ContentfulSDK\ManagementSDK;
    $managementSDK = new ManagementSDK('TOKEN', 'SPACE_ID');

Token: Your Contentful OAuth token.

Space ID: (optional) The space to use for calls made by the instance. To use multiple spaces, you should use multiple SDK instances. If you don't provide a space ID, you'll only be able to use the spaces resource.

Note that there is a third parameter for the cacher. Management API calls are not currently cached to make sure that GET requests are up to date to avoid conflicts when updating records. I still wanted to allow a place to provide the cacher just in case I decide to use it for anything. Feel free to ignore it, or provide a cacher for good measure.

####Using Builder Objects Contentful payloads can be complex, especially when working with entries or assets. Payload builders are here to help! They're optional helper classes to assist with building payloads. They take care of building payload arrays for you and let you know what options you have along the way. They're especially helpful if your IDE has hinting.

If you don't want to use them, don't use them. The SDK parases the payload looking for builder objects and turns them into arrays before passing requests on to Contentful. As such, you are free to use standard arrays, or arrays made up of payload builder objects.

The following examples will assume you're using the builders you need:

use Incraigulous\ContentfulSDK\PayloadBuilders\Entry;
use Incraigulous\ContentfulSDK\PayloadBuilders\EntryField;
use Incraigulous\ContentfulSDK\PayloadBuilders\Space;
...

####Spaces

#####Creating a space

$result = $managementSDK->spaces()
				->post(
					new Space('My Space')
				);

#####Updating a space

$space = $managementSDK->spaces()
             ->find('SPACE_ID')
             ->get();
             
$space['name'] = 'Outer Space';
$result = $managementSDK->spaces()->put('SPACE_ID', $space);

#####Deleting a space

$result = $managementSDK->spaces()->delete('SPACE_ID');

####Content Types

#####Creating a content type

$result = $managementSDK->contentTypes()
                ->post(
                    new ContentType('Blog Post', 'title', [
                        new ContentTypeField('title', 'Title', 'Text'),
                        new ContentTypeField('body', 'Body', 'Text'),
                    ])
                );
            );

#####Creating a content type with validation and links

$result = $managementSDK->contentTypes()
                ->post(
                    new ContentType('Blog Post', 'title', [
                        new ContentTypeField('title', 'Title', 'Text'),
                        new ContentTypeField('body', 'Body', 'Text'),
                        (new ContentTypeField('author', 'Field List', 'Link'))->setLink('Entry'),
                        (new ContentTypeField('sidebar', 'Field List', 'Array'))->setMultiLink('Entry'),
                        (new ContentTypeField('category', 'Category', 'Text'))->setValidations((new ContentTypeValidation())->in(['Design', 'Development'])),
                    ])
                );

#####Updating a content type

$contentType = $managementSDK->contentTypes()
					->find('CONTENT_TYPE_ID')
					->get();

$contentType['fields'][0]['name'] = 'Post Title';
$result = $managementSDK->contentTypes()->put('CONTENT_TYPE_ID', $contentType);

#####Publishing a content type

$contentType = $managementSDK->contentTypes()
					->find('CONTENT_TYPE_ID')
					->get();

$result = $managementSDK->contentTypes()->publish('CONTENT_TYPE_ID', $contentType);

#####Unublishing a content type

$contentType = $managementSDK->contentTypes()
					->find('CONTENT_TYPE_ID')
					->get();

$result = $managementSDK->contentTypes()->unpublish('CONTENT_TYPE_ID', $contentType);

#####Deleting a content type

$result = $managementSDK->contentTypes()->delete('CONTENT_TYPE_ID');

#####Content Type Payload Builder

#####Content Type Field Payload Builder

#####Content Type Field Validations Payload Builder

Takes no parameters.

####Entries

#####Creating an entry

$result = $managementSDK->entries()->contentType('CONTENT_TYPE_ID')->post(
            new Entry([
                    new EntryField('title', 'Hello, World!'), //Create a field with only the default language
                    (new EntryField('body'))->addLanguage('en-US', 'Bacon is healthy!') //Add a language to a field.
                ])
        );

Note that you are able to add content to a field without specifying a language. The default default language is en-US. To specify a different default language, define a CONTENTFUL_DEFAULT_LANGUAGE constant.

Example:

define('CONTENTFUL_DEFAULT_LANGUAGE', 'de-DE'); 

#####Creating an entry while specifying an ID

$result = $managementSDK->entries()->put('MY_CUSTOM_ID', 
		new Entry([
                    new EntryField('title', 'Hello, World!'),
                    (new EntryField('body'))->addLanguage('en-US', 'Bacon is healthy!')
                ])
        );

#####Creating an entry with a linked field

$result = $managementSDK->entries()->contentType('CONTENT_TYPE_ID')->post(new Entry([
            new EntryField('title', 'Hello, World!'),
           (new EntryField('body'))->addLanguage('en-US', 'Bacon is healthy!'),
           (new EntryField('sidebar'))->addMultiLink('ENTRY_ID', 'Entry')->addMultiLink('ENTRY_ID', 'Entry'),
           (new EntryField('author'))->addLink('ENTRY_ID', 'Entry')
        ]));

#####Updating an entry

$entry = $managementSDK->entries()
					->find('ENTRY_ID')
					->get();

$entry['fields']['title'] = new EntryField('title', 'Cheese is Healthy!');
$result = $managementSDK->entries()->put('ENTRY_ID', $entry);

#####Publishing an entry

$entry = $managementSDK->entries()->find('ENTRY_ID')->get();
$result = $managementSDK->entries()->publish('ENTRY_ID', $entry);

#####Unpublishing an entry

$entry = $managementSDK->entries()->find('ENTRY_ID')->get();
$result = $managementSDK->entries()->unpublish('ENTRY_ID', $entry);

#####Archiving an entry

$result = $managementSDK->entries()->archive('ENTRY_ID');

#####Unarchiving an entry

$result = $managementSDK->entries()->unarchive('ENTRY_ID');

#####Deleting an entry

$result = $managementSDK->entries()->delete('ENTRY_ID');

#####Entry Payload Builder

#####Entry Field Payload Builder

####Assets

#####Creating an asset

$result = $managementSDK->assets()->post(new Asset([
                    new AssetField('title', 'Bacon Pancakes'),
                    new File("image/jpeg", "example.jpg", "https://example.com/example.jpg")
                ])
        );

#####Creating an asset while specifying an ID

$result = $managementSDK->assets()->put('MY_CUSTOM_ID', new Asset([
                    new AssetField('title', 'Bacon Pancakes'),
                    new File("image/jpeg", "example.jpg", "https://example.com/example.jpg")
                ])
        );

#####Updating an asset

$asset = $managementSDK->assets()->find('ASSET_ID')->get();

$asset['fields']['file'] = new File("image/jpeg", "example.jpg", "https://example.com/example.jpg");
$result = $managementSDK->assets()->put('ASSET_ID', $asset);

#####Processing an asset

$result = $managementSDK->assets()->process('ASSET_ID');

#####Publishing an asset

$asset = $managementSDK->assets()->find('ASSET_ID')->get();
$result = $managementSDK->assets()->publish('ASSET_ID', $asset);

#####Unpublishing an asset

$asset = $managementSDK->assets()->find('ASSET_ID')->get();
$result = $managementSDK->assets()->unpublish('ASSET_ID', $asset);

#####Archiving an asset

$result = $managementSDK->assets()->archive('ASSET_ID');

#####Unarchiving an asset

$result = $managementSDK->assets()->unarchive('ASSET_ID');

#####Deleting an asset

$result = $managementSDK->assets()->delete('ASSET_ID');

#####Asset Payload Builder

#####Asset Field Payload Builder

#####File Payload Builder

####Webhooks

#####Creating a webhook

$result = $managementSDK->webhooks()->post(
			new Webhook('http://www.example.com/')
		);

#####Updating a webhook, or creating new a webhook with a set ID

$result = $managementSDK->webhooks()->put('WEBHOOK_ID', 
			new Webhook('http://www.example.com/')
		);

#####Deleting a webhook

$result = $managementSDK->webhooks()->delete('WEBHOOK_ID');

#####Webhook Payload Builder

###What's not implemented?

###Contributing

See a typo or a bug? Make a pull request.
What a new feature? Make a pull request.
Want a new feature and don't know how to build it? You can always ask, I might be game if I think it's a good enough idea.

####How you can help I'm going to make issues for features that I would like implemented. I'll assign them to myself if I plan to take to build them out. If I leave them unasigned, please step up and take it!