PHPackages                             dotcms/php-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. dotcms/php-sdk

ActiveLibrary[API Development](/categories/api)

dotcms/php-sdk
==============

The `dotcms-php-sdk` is a PHP library designed to simplify interaction with the dotCMS Page API

1.0.1(11mo ago)124[1 PRs](https://github.com/dotCMS/dotcms-php-sdk/pulls)MITPHPPHP ^8.2CI passing

Since Mar 21Pushed 10mo ago2 watchersCompare

[ Source](https://github.com/dotCMS/dotcms-php-sdk)[ Packagist](https://packagist.org/packages/dotcms/php-sdk)[ RSS](/packages/dotcms-php-sdk/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (11)Versions (19)Used By (0)

dotCMS PHP SDK (`alpha`)
========================

[](#dotcms-php-sdk-alpha)

A PHP library designed to simplify interaction with the dotCMS Page API. This SDK provides a clean, object-oriented interface for retrieving and working with dotCMS pages and their components.

[![PHP Code Quality Checks](https://github.com/dotCMS/dotcms-php-sdk/actions/workflows/php-quality-checks.yml/badge.svg)](https://github.com/dotCMS/dotcms-php-sdk/actions/workflows/php-quality-checks.yml)

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Composer

Installation
------------

[](#installation)

Install the SDK using Composer:

```
composer require dotcms/php-sdk
```

Configuration
-------------

[](#configuration)

The SDK requires configuration to connect to your dotCMS instance:

```
use Dotcms\PhpSdk\Config\Config;

// Create a configuration for the client
$config = new Config(
    host: 'https://your-dotcms-instance.com',
    apiKey: 'YOUR_API_KEY',
    clientOptions: [
        'timeout' => 30
    ]
);
```

### Configuration Options

[](#configuration-options)

#### Required Parameters

[](#required-parameters)

- `host`: Your dotCMS instance URL
- `apiKey`: Your dotCMS API key

#### Optional Parameters

[](#optional-parameters)

- `clientOptions`: Guzzle HTTP client options

    - `headers`: Custom HTTP headers
    - `verify`: SSL verification (boolean)
    - `timeout`: Request timeout in seconds
    - `connect_timeout`: Connection timeout in seconds
    - `http_errors`: Whether to throw exceptions for HTTP errors
    - `allow_redirects`: Whether to follow redirects
- `logConfig`: Logging configuration

    - `level`: Log level (DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY)
    - `console`: Whether to output logs to console
    - `handlers`: Array of custom Monolog handlers

Basic Usage
-----------

[](#basic-usage)

### Creating a Client

[](#creating-a-client)

```
use Dotcms\PhpSdk\DotCMSClient;

// Create the dotCMS client
$client = new DotCMSClient($config);
```

### Fetching a Page

[](#fetching-a-page)

```
try {
    // Create a page request for a specific page
    $pageRequest = $client->createPageRequest('/', 'json');

    // Get the page
    $pageAsset = $client->getPage($pageRequest);

    // Access page information
    echo "Page title: " . $pageAsset->page->title . "\n";
    echo "Page URL: " . $pageAsset->page->pageUrl . "\n";
    echo "Template name: " . $pageAsset->template->title . "\n";

    // Check if page has vanity URL
    if ($pageAsset->vanityUrl !== null) {
        echo "Vanity URL: " . $pageAsset->vanityUrl->url . "\n";
        echo "Forward to: " . $pageAsset->vanityUrl->forwardTo . "\n";
    }

} catch (\Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
```

### Fetching Navigation

[](#fetching-navigation)

```
try {
    // Create a navigation request
    $navRequest = $client->createNavigationRequest('/about-us', 2);

    // Get the navigation
    $nav = $client->getNavigation($navRequest);

    // Access navigation information
    echo "Navigation title: " . $nav->title . "\n";
    echo "Navigation URL: " . $nav->href . "\n";

    // Access children if available
    if ($nav->hasChildren()) {
        foreach ($nav->getChildren() as $child) {
            echo "- " . $child->title . " (" . $child->href . ")\n";
        }
    }

} catch (\Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
```

### Asynchronous Requests

[](#asynchronous-requests)

```
// Create a page request
$asyncPageRequest = $client->createPageRequest('/', 'json');

// Get the page asynchronously
$promise = $client->getPageAsync($asyncPageRequest);

// Add callbacks for success and failure
$promise->then(
    function ($asyncPage) {
        echo "Async page title: " . $asyncPage->page->title . "\n";
        if ($asyncPage->vanityUrl !== null) {
            echo "Vanity URL: " . $asyncPage->vanityUrl->url . "\n";
        }
    },
    function (\Exception $e) {
        echo "Error: " . $e->getMessage() . "\n";
    }
);

// Wait for the promise to complete
$promise->wait();
```

### Asynchronous Navigation Requests

[](#asynchronous-navigation-requests)

```
// Create a navigation request
$asyncNavRequest = $client->createNavigationRequest('/', 2);

// Get the navigation asynchronously
$promise = $client->getNavigationAsync($asyncNavRequest);

// Add callbacks for success and failure
$promise->then(
    function ($nav) {
        echo "Navigation title: " . $nav['title'] . "\n";
        if ($nav->hasChildren()) {
            foreach ($nav->getChildren() as $child) {
                echo "- " . $child['title'] . "\n";
            }
        }
    },
    function (\Exception $e) {
        echo "Error: " . $e->getMessage() . "\n";
    }
);

// Wait for the promise to complete
$promise->wait();
```

Advanced Usage
--------------

[](#advanced-usage)

### Customizing Page Requests

[](#customizing-page-requests)

The `PageRequest` class provides several methods to customize your page requests:

```
$pageRequest = $client->createPageRequest('/about-us', 'json');

// Set the language ID for the request
$pageRequest = $pageRequest->withLanguageId(1);

// Set the mode (LIVE, WORKING, EDIT_MODE)
$pageRequest = $pageRequest->withMode('WORKING');

// Set the depth of the content to retrieve (0-3)
$pageRequest = $pageRequest->withDepth(2);

// Set personalization options
$pageRequest = $pageRequest->withPersonaId('persona_id');

// Set whether to fire rules
$pageRequest = $pageRequest->withFireRules(true);

// Set the host ID (Site ID)
$pageRequest = $pageRequest->withHostId('48190c8c-42c4-46af-8d1a-0cd5db894797');
```

Note that each method returns a new instance with the updated value, so you need to reassign the result.

### Customizing Navigation Requests

[](#customizing-navigation-requests)

The `NavigationRequest` class allows you to customize your navigation requests:

```
// Create a navigation request with custom parameters
$navRequest = $client->createNavigationRequest(
    path: '/about-us',  // The root path to begin traversing
    depth: 2,           // The depth of the folder tree to return (1-3)
    languageId: 2       // The language ID for content (e.g., 2 for Spanish)
);

// Get the navigation with the custom parameters
$nav = $client->getNavigation($navRequest);
```

### Working with Page Components

[](#working-with-page-components)

Once you have a page, you can access its components:

```
// Access site information
echo "Site hostname: " . $page->site->hostname . "\n";

// Access template information
echo "Template title: " . $page->template->title . "\n";

// Access layout information
echo "Layout header: " . $page->layout->header . "\n";

// Access vanity URL if present
if ($page->vanityUrl !== null) {
    echo "Vanity URL pattern: " . $page->vanityUrl->pattern . "\n";
    echo "Forward to: " . $page->vanityUrl->forwardTo . "\n";
    echo "Response code: " . $page->vanityUrl->response . "\n";
    echo "Is temporary redirect: " . ($page->vanityUrl->temporaryRedirect ? 'Yes' : 'No') . "\n";
}

// Access containers and contentlets
foreach ($page->containers as $containerId => $container) {
    echo "Container ID: " . $containerId . "\n";
    echo "Max Contentlets: " . $container->maxContentlets . "\n";

    if (!empty($container->contentlets)) {
        foreach ($container->contentlets as $uuid => $contentlets) {
            foreach ($contentlets as $contentlet) {
                echo "Contentlet type: " . $contentlet->contentType . "\n";
                echo "Contentlet title: " . ($contentlet->title ?? 'N/A') . "\n";

                // Access additional fields using object properties
                foreach ($contentlet->getAdditionalProperties() as $fieldName => $fieldValue) {
                    if (is_scalar($fieldValue)) {
                        echo "$fieldName: $fieldValue\n";
                    }
                }
            }
        }
    }
}
```

### Working with Navigation Items

[](#working-with-navigation-items)

The `NavigationItem` class provides array access to its properties:

```
// Check if the navigation item is a folder
if ($nav->isFolder()) {
    echo "This is a folder\n";
}

// Check if the navigation item is a page
if ($nav->isPage()) {
    echo "This is a page\n";
}

// Access navigation properties
echo "Title: " . $nav->title . "\n";
echo "URL: " . $nav->href . "\n";
echo "Type: " . $nav->type . "\n";
echo "Target: " . $nav->target . "\n"; // e.g., "_self", "_blank"
echo "Order: " . $nav->order . "\n";

// Recursively process navigation tree
function processNavigation($navItem, $level = 0) {
    $indent = str_repeat("  ", $level);
    echo $indent . "- " . $navItem->title . " (" . $navItem->href . ")\n";

    if ($navItem->hasChildren()) {
        foreach ($navItem->getChildren() as $child) {
            processNavigation($child, $level + 1);
        }
    }
}

processNavigation($nav);
```

### Using SDK Utilities

[](#using-sdk-utilities)

The SDK includes a `DotCmsHelper` class with common functions for rendering and working with DotCMS content:

```
use Dotcms\PhpSdk\Utils\DotCmsHelper;
use Dotcms\PhpSdk\Model\Content\Contentlet;

// Generate HTML attributes from an associative array
$attrs = [
    'class' => 'my-class',
    'data-id' => '123',
    'disabled' => true
];
$htmlAttrs = DotCmsHelper::htmlAttributes($attrs);

// Generate simple HTML for a contentlet
$contentlet = new Contentlet(
    identifier: 'abc123',
    inode: 'inode123',
    title: 'My Content',
    contentType: 'Banner'
);
$html = DotCmsHelper::simpleContentHtml($contentlet->jsonSerialize());

// Extract accept types from container structures
$acceptTypes = DotCmsHelper::extractAcceptTypes($containerStructures);

// Extract contentlets from container page
$contentlets = DotCmsHelper::extractContentlets($containerPage, $uuid);
```

These utilities help with common tasks like:

- Generating HTML attributes safely
- Rendering contentlets with basic HTML
- Working with container structures and contentlets
- Extracting data from container pages

Data Access Patterns
--------------------

[](#data-access-patterns)

The SDK provides two ways to access data: object notation and array access. Here's when to use each:

### Object Notation (-&gt;)

[](#object-notation--)

Use object notation for accessing standard properties of these classes:

```
// Page and Site properties
$page->title
$page->pageUrl
$site->hostname

// Container properties
$container->identifier
$container->title
$container->maxContentlets

// Contentlet properties
$contentlet->identifier
$contentlet->title
$contentlet->contentType

// Navigation properties
$nav->title
$nav->href
$nav->type
```

### Array Access (\[\])

[](#array-access-)

Use array access for:

1. Additional properties not explicitly defined in the class
2. Accessing container contentlets by UUID
3. Accessing rendered content by UUID

```
// Additional properties
$contentlet['customField']
$page['metadata']

// Container contentlets
$container->contentlets['uuid-123']

// Rendered content
$container->rendered['uuid-123']
```

### Classes That Support Both

[](#classes-that-support-both)

These classes support both object and array access:

- `Page`
- `Site`
- `Contentlet`
- `Container`
- Any class extending `AbstractModel`

### Classes That Only Support Object Access

[](#classes-that-only-support-object-access)

These classes only support object notation:

- `PageAsset`
- `ContainerPage`
- `NavigationItem`
- `Layout`
- `Template`
- `VanityUrl`

API Reference
-------------

[](#api-reference)

### DotCMSClient

[](#dotcmsclient)

The main client for interacting with the dotCMS API.

MethodDescriptionParameters`__construct`Create a new client instance`Config $config``getPage`Fetch a page synchronously`PageRequest $request``getPageAsync`Fetch a page asynchronously`PageRequest $request``createPageRequest`Create a new page request`string $pagePath, string $format = 'json'``getNavigation`Fetch navigation items synchronously`NavigationRequest $request``getNavigationAsync`Fetch navigation items asynchronously`NavigationRequest $request``createNavigationRequest`Create a new navigation request`string $path = '/', int $depth = 1, int $languageId = 1`### PageRequest

[](#pagerequest)

Represents a request to the dotCMS Page API.

MethodDescriptionParameters`__construct`Create a new page request`string $pagePath, string $format = 'json'``withLanguageId`Set the language ID for the request`int $languageId``withMode`Set the mode (LIVE, WORKING, EDIT\_MODE)`string $mode``withDepth`Set the depth of the content to retrieve (0-3)`int $depth``withPersonaId`Set the persona ID for personalization`string $personaId``withHostId`Set the host ID (Site ID)`string $hostId``withFireRules`Set whether to fire rules`bool $fireRules``buildPath`**(Internal)** Build the API path for the requestNone`buildQueryParams`**(Internal)** Build the query parameters for the requestNone### NavigationRequest

[](#navigationrequest)

Represents a request to the dotCMS Navigation API.

MethodDescriptionParameters`__construct`Create a new navigation request`string $path = '/', int $depth = 1, int $languageId = 1``getPath`Get the pathNone`getDepth`Get the depthNone`getLanguageId`Get the language IDNone`buildPath`**(Internal)** Build the API path for the requestNone`buildQueryParams`**(Internal)** Build the query parameters for the requestNone### PageAsset

[](#pageasset)

Represents a complete page asset from dotCMS.

PropertyTypeDescription`page`PageThe Page object`site`SiteThe Site object`template`TemplateThe Template object`layout`LayoutThe Layout object`containers`arrayArray of ContainerPage objects`urlContentMap`Contentlet|nullContent map for generated pages`viewAs`ViewAsVisitor context information`vanityUrl`VanityUrl|nullOptional vanity URL configuration### ContainerPage

[](#containerpage)

Represents a container page from dotCMS.

PropertyTypeDescription`container`ContainerThe Container object`containerStructures`arrayArray of ContainerStructure objects`rendered`array&lt;string, string&gt;Rendered content keyed by UUID`contentlets`array&lt;string, array&gt;Contentlets keyed by UUID### Contentlet

[](#contentlet)

Represents a content item from dotCMS.

PropertyTypeDescription`identifier`stringThe content identifier`inode`stringThe content inode`title`stringThe content title`contentType`stringThe content type`additionalProperties`array&lt;string, mixed&gt;Additional content propertiesMethodDescriptionReturn Type`getAdditionalProperties`Get additional properties`array``jsonSerialize`Convert to array for JSON serialization`array`### DotCmsHelper

[](#dotcmshelper)

Utility class for common DotCMS operations.

MethodDescriptionParametersReturn Type`htmlAttributes`Generate HTML attributes`array``string``simpleContentHtml`Generate simple HTML for content`array``string``extractAcceptTypes`Extract accept types from structures`array``string``extractContentlets`Extract contentlets from container`ContainerPage, string``array`Error Handling
--------------

[](#error-handling)

The SDK provides several exception classes for error handling:

ExceptionDescription`DotCMSException`Base exception class for all SDK exceptions`ConfigException`Thrown when there's an issue with the configuration`HttpException`Thrown when there's an HTTP error`ResponseException`Thrown when there's an issue with the responseExample error handling:

```
try {
    $pageAsset = $client->getPage($pageRequest);
} catch (ConfigException $e) {
    echo "Configuration error: " . $e->getMessage() . "\n";
} catch (HttpException $e) {
    echo "HTTP error: " . $e->getMessage() . "\n";
    echo "Status code: " . $e->getStatusCode() . "\n";
} catch (ResponseException $e) {
    echo "Response error: " . $e->getMessage() . "\n";
} catch (DotCMSException $e) {
    echo "dotCMS error: " . $e->getMessage() . "\n";
} catch (\Exception $e) {
    echo "General error: " . $e->getMessage() . "\n";
}
```

Examples
--------

[](#examples)

### Basic Page Example

[](#basic-page-example)

```
