Skip to content

Latest commit

 

History

History
295 lines (244 loc) · 5.95 KB

Tutorial.md

File metadata and controls

295 lines (244 loc) · 5.95 KB

DatoCMS PHP SDK: Complete Documentation 📚

Version: 1.0
Author: Milton Vafana
License: MIT


Table of Contents

  1. Overview
  2. Installation
  3. Configuration
  4. Basic Usage
  5. Advanced Features
  6. Examples
  7. Troubleshooting
  8. Best Practices
  9. Support

1. Overview

A PHP SDK to interact with DatoCMS's GraphQL API. Designed for:

  • Building PHP applications with content managed in DatoCMS
  • Migrating content between environments
  • Creating custom integrations

Key Features:

  • ✅ Simple data fetching
  • 🖼 File/asset uploads
  • 🔄 Automatic retry logic
  • 🛡️ Robust error handling

2. Installation

Step 1: Install Composer

Skip if already installed:

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

Step 2: Create Project Folder

mkdir my-datocms-app
cd my-datocms-app

Step 3: Install SDK

composer require nia-cloud-official/datocms-php-sdk

3. Configuration

Step 1: Get API Token

  1. Log in to DatoCMS
  2. Go to Settings > API Tokens
  3. Copy Read-only API token

Step 2: Create .env File

touch .env

Add your token:

# .env
DATOCMS_API_TOKEN=your_token_here

Step 3: Basic Setup File

Create app.php:

<?php
require 'vendor/autoload.php';

use DatoCMS\Client;

// Load environment variables
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Initialize client
$client = new Client('DATOCMS_API_TOKEN');

4. Basic Usage

4.1 Fetching Data

Example: Get blog posts

try {
    $result = $client->query('
        query {
            allPosts {
                id
                title
                content
            }
        }
    ');
    
    foreach ($result['allPosts'] as $post) {
        echo "Title: {$post['title']}\n";
    }
    
} catch (Exception $e) {
    die("Error: " . $e->getMessage());
}

4.2 Creating Content

$mutation = '
    mutation CreatePost($title: String!, $content: String!) {
        createPost(
            title: $title
            content: $content
        ) {
            id
        }
    }
';

$variables = [
    'title' => 'New Post',
    'content' => 'Hello World!'
];

$result = $client->query($mutation, $variables);

4.3 Updating Content

$mutation = '
    mutation UpdatePost($id: ID!, $title: String!) {
        updatePost(
            id: $id
            title: $title
        ) {
            id
            title
        }
    }
';

$variables = [
    'id' => '123',
    'title' => 'Updated Title'
];

4.4 Deleting Content

$mutation = '
    mutation DeletePost($id: ID!) {
        deletePost(id: $id) {
            id
        }
    }
';

$variables = ['id' => '123'];

5. Advanced Features

5.1 File Uploads

try {
    $file = $client->uploadFile('/path/to/image.jpg');
    echo "Uploaded file URL: {$file['url']}";
} catch (ApiException $e) {
    die("Upload failed: " . $e->getMessage());
}

5.2 Error Handling

Handle specific errors:

try {
    // Your code here
} catch (AuthException $e) {
    die("❌ Invalid API token! Check your .env file");
} catch (RateLimitException $e) {
    sleep(60); // Wait 1 minute
    retry();
} catch (ApiException $e) {
    error_log($e->getMessage());
    die("A wild error appeared! 🐞");
}

6. Real-World Examples

Example 1: Blog System

// Get latest 5 posts with images
$result = $client->query('
    query {
        allPosts(orderBy: [date_DESC], first: 5) {
            title
            excerpt
            coverImage {
                url
                alt
            }
        }
    }
');

foreach ($result['allPosts'] as $post) {
    echo "<article>
        <img src='{$post['coverImage']['url']}' alt='{$post['coverImage']['alt']}'>
        <h2>{$post['title']}</h2>
        <p>{$post['excerpt']}</p>
    </article>";
}

Example 2: User Profile Update

$mutation = '
    mutation UpdateUser($id: ID!, $bio: String!) {
        updateUser(id: $id, bio: $bio) {
            id
            bio
        }
    }
';

$client->query($mutation, [
    'id' => 'user-456',
    'bio' => 'PHP developer passionate about CMS integrations'
]);

7. Troubleshooting

Error Solution
401 Unauthorized 1. Check .env file
2. Verify token in DatoCMS dashboard
Could not resolve host Check internet connection
File upload failed 1. Verify file exists
2. Check file permissions
Unexpected JSON error Validate your GraphQL query

8. Best Practices

  1. Never commit .env
    Add to .gitignore:
    echo ".env" >> .gitignore
  2. Use query variables
    Avoid string interpolation in GraphQL queries
  3. Implement caching
    Example with Redis:
    $client = new Client($_ENV['DATOCMS_API_TOKEN'], [
        'cache' => new RedisCache()
    ]);
  4. Validate inputs
    Sanitize data before sending to DatoCMS

9. Support

Need Help?
Contact: miltonhyndrex@gmail.com

Official Resources: