Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Contentful Laravel Package

atolye15/contentful

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require atolye15/contentful
    
  2. Basic Client Initialization

    use Atolye15\Contentful\Client;
    
    $client = new Client([
        'space' => env('CONTENTFUL_SPACE_ID'),
        'accessToken' => env('CONTENTFUL_ACCESS_TOKEN'),
        'host' => env('CONTENTFUL_HOST', 'cdn.contentful.com'),
    ]);
    
  3. First Use Case: Fetching an Entry

    $entry = $client->getEntry('YOUR_ENTRY_ID');
    echo $entry->getField('title');
    

Key Starting Points

  • Configuration: Check .env for CONTENTFUL_SPACE_ID, CONTENTFUL_ACCESS_TOKEN, and CONTENTFUL_HOST.
  • API Docs: Reference Contentful’s Delivery API for field types and endpoints.
  • Entry Model: The Entry class is the primary object for interacting with content.

Implementation Patterns

Common Workflows

1. Fetching Content

// Single entry
$entry = $client->getEntry('entryId');

// Entries by content type
$entries = $client->getEntriesByContentType('blogPost');

// Entries with a query
$entries = $client->getEntries([
    'content_type' => 'blogPost',
    'query' => 'laravel',
    'limit' => 10,
]);

2. Handling Assets

$asset = $client->getAsset('assetId');
$assetUrl = $asset->getUrl(); // Direct URL to the asset

3. Localization

$entry = $client->getEntry('entryId', 'fr-FR'); // French locale

4. Integration with Laravel

  • Service Provider:

    $this->app->singleton(Client::class, function ($app) {
        return new Client([
            'space' => config('contentful.space_id'),
            'accessToken' => config('contentful.access_token'),
        ]);
    });
    
  • Facade (Optional): Publish the facade and create ContentfulServiceProvider to bind the client.

  • Eloquent Model Binding:

    use Atolye15\Contentful\Eloquent\HasContentfulEntries;
    
    class BlogPost extends Model
    {
        use HasContentfulEntries;
    
        protected $contentfulType = 'blogPost';
    }
    

5. Caching Responses

$client = new Client([
    'space' => '...',
    'accessToken' => '...',
    'cache' => new \Atolye15\Contentful\Cache\ArrayCache(), // Or use Laravel's cache
]);

Integration Tips

  • Environment Variables: Always use .env for sensitive data like accessToken.
  • Error Handling: Wrap API calls in try-catch blocks to handle Atolye15\Contentful\Exception\ContentfulException.
  • Field Access: Use getField() or getFields() for structured data. Example:
    $title = $entry->getField('title');
    $fields = $entry->getFields(); // All fields as an array
    
  • Pagination: Use getEntries() with limit and offset for paginated results.
  • Webhooks: For real-time updates, consider using Contentful’s webhooks alongside this SDK.

Gotchas and Tips

Pitfalls

  1. Deprecated Methods:

    • Avoid using get() directly on Entry or Asset objects. Prefer getField() or getFields() for consistency.
    • Example of deprecated usage:
      // ❌ Avoid
      $entry->get('title');
      
      // ✅ Use instead
      $entry->getField('title');
      
  2. Locale Handling:

    • If no locale is specified, the SDK defaults to en-US. Explicitly pass locales for non-English content.
    • Example:
      $entry = $client->getEntry('entryId', 'es-ES'); // Spanish locale
      
  3. Caching Quirks:

    • The default ArrayCache is in-memory and not persistent. Use Laravel’s cache or a persistent solution (e.g., Redis) for production.
    • Cache invalidation is manual. Clear cache when content is updated via Contentful’s web app or webhooks.
  4. Field Type Mismatches:

    • The SDK returns fields as arrays or objects based on their Contentful type. Always validate field types before processing.
    • Example:
      $entry = $client->getEntry('entryId');
      if ($entry->getField('author') instanceof \Atolye15\Contentful\Entry) {
          // Handle linked entry
      }
      
  5. Rate Limiting:

    • Contentful enforces rate limits. Monitor your API calls, especially in loops or cron jobs.
    • Use exponential backoff for retries if needed.

Debugging Tips

  1. Enable Debugging:

    $client = new Client([
        'space' => '...',
        'accessToken' => '...',
        'debug' => true, // Enable debug mode
    ]);
    
    • Debug logs will be output to stderr.
  2. HTTP Client Inspection:

    • The SDK uses Guzzle under the hood. You can inspect raw requests/responses by extending the Client class or using middleware:
      $client->getHttpClient()->getEmitter()->attach(
          new \GuzzleHttp\Middleware();
      );
      
  3. Common Errors:

    • 404 Not Found: Verify space, entryId, or assetId are correct.
    • 401 Unauthorized: Check accessToken permissions in Contentful’s API keys section.
    • 429 Too Many Requests: Implement retries with backoff.

Extension Points

  1. Custom Field Types:

    • Extend the Atolye15\Contentful\Field class to handle custom field types or transformations.
    • Example:
      class CustomField extends \Atolye15\Contentful\Field
      {
          public function getFormattedValue()
          {
              return $this->value . ' (custom)';
          }
      }
      
  2. Middleware:

    • Add middleware to the HTTP client for logging, auth, or request modification:
      $client->getHttpClient()->getEmitter()->attach(
          function (callable $handler) {
              return function ($request, $options) use ($handler) {
                  // Modify request or options
                  return $handler($request, $options);
              };
          }
      );
      
  3. Event Listeners:

    • Listen for events like entry.fetched or asset.fetched by extending the Client class and overriding methods.
  4. Testing:

    • Use the ContentfulTestCase base class (if available) or mock the Client in tests:
      $mockClient = Mockery::mock(Client::class);
      $mockClient->shouldReceive('getEntry')->andReturn($mockEntry);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware