nia-cloud-official / datocms-php-sdk
PHP SDK for DatoCMS
v1.0.1
2025-02-21 20:56 UTC
Requires
- php: ^7.4|^8.0
- guzzlehttp/guzzle: ^7.0
README
A PHP client for interacting with DatoCMS's GraphQL API. Perfect for building PHP applications with content managed in DatoCMS.
Features:
- ✅ CRUD operations
- 🖼 File uploads
- 🔄 Automatic retry logic
- 🛡️ Robust error handling
- 📦 Composer ready
Table of Contents
Installation 📦
-
Require via Composer:
composer require nia-cloud-official/datocms-php-sdk
-
Create
.env
file:DATOCMS_API_TOKEN=your_api_token_here
-
Get API token:
- Go to DatoCMS → Settings → API Tokens
- Copy Read-only API token
Quick Start ⚡
<?php require 'vendor/autoload.php'; use DatoCMS\Client; $client = new Client(getenv('DATOCMS_API_TOKEN')); try { // Get all blog posts $result = $client->query(' query { allPosts { title content } } '); print_r($result); } catch (Exception $e) { die("Error: " . $e->getMessage()); }
Basic Usage 📖
Fetch Data
$result = $client->query(' query GetPost($id: ID!) { post(filter: {id: {eq: $id}}) { title content } } ', ['id' => '123']);
Create Content
$client->query(' mutation CreatePost($title: String!) { createPost(title: $title) { id } } ', ['title' => 'New Post']);
Upload File
$file = $client->uploadFile('/path/to/image.jpg'); echo "Uploaded to: " . $file['url'];
Advanced Features 🧠
Error Handling
try { // Your code here } catch (DatoCMS\Exceptions\AuthException $e) { die("Invalid API token! 💀"); } catch (DatoCMS\Exceptions\RateLimitException $e) { sleep(60); // Wait 1 minute } catch (Exception $e) { error_log($e->getMessage()); }
Best Practices
- Cache responses:
$client = new Client(getenv('DATOCMS_API_TOKEN'), [ 'cache' => new RedisCache() ]);
- Use query variables
- Validate inputs before sending
Troubleshooting 🔧
Error | Solution |
---|---|
401 Unauthorized |
Check .env file |
429 Too Many Requests |
Implement retry logic |
File upload failed |
Check file permissions |
Unexpected response |
Validate GraphQL query |
Contributing 🤝
- Fork the repository
- Create your feature branch:
git checkout -b feature/amazing-feature
- Commit changes:
git commit -m 'Add amazing feature'
- Push to branch:
git push origin feature/amazing-feature
- Open a Pull Request
License 📄
This project is licensed under the MIT License - see the LICENSE file for details.
Need Help?
Email: miltonhyndrex@gmail.com
Official Docs: DatoCMS Documentation