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

Strapi Client Bundle Laravel Package

ahc/strapi-client-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ahc/strapi-client-bundle
    

    Ensure your project uses Symfony 4/5 and PHP 7.4+.

  2. Enable the Bundle Add to config/bundles.php (Symfony 4.4+):

    return [
        // ...
        Ahc\StrapiClientBundle\AhcStrapiClientBundle::class => ['all' => true],
    ];
    
  3. Configure Strapi Connection Publish the default config:

    php bin/console config:dump-reference AhcStrapiClientBundle
    

    Update config/packages/ahc_strapi_client.yaml:

    ahc_strapi_client:
        base_uri: 'http://your-strapi-instance.local/api'
        api_token: 'your-api-token-here'
    
  4. First Use Case: Fetching Content Inject the client into a service/controller:

    use Ahc\StrapiClientBundle\Client\StrapiClientInterface;
    
    class MyController extends AbstractController
    {
        public function __construct(private StrapiClientInterface $strapiClient) {}
    
        public function showPosts()
        {
            $posts = $this->strapiClient->get('/posts');
            return $this->render('posts/index.html.twig', ['posts' => $posts]);
        }
    }
    

Implementation Patterns

Core Workflows

  1. RESTful API Integration

    • GET Requests: Fetch collections or single entries.
      $posts = $this->strapiClient->get('/posts');
      $singlePost = $this->strapiClient->get('/posts/1');
      
    • POST/PUT/DELETE: CRUD operations.
      $newPost = $this->strapiClient->post('/posts', ['title' => 'Hello']);
      $this->strapiClient->put('/posts/1', ['title' => 'Updated']);
      $this->strapiClient->delete('/posts/1');
      
  2. Pagination & Filtering Use query parameters for Strapi’s built-in features:

    $filteredPosts = $this->strapiClient->get('/posts', [
        'filters' => ['published_at' => ['$ne' => null]],
        'pagination' => ['pageSize' => 10, 'page' => 2],
    ]);
    
  3. Uploading Media Use the uploadMedia method for file uploads:

    $media = $this->strapiClient->uploadMedia(
        '/upload',
        'path/to/file.jpg',
        ['field' => 'image'] // Optional field mapping
    );
    
  4. Relationships Fetch related data via populate:

    $postsWithAuthors = $this->strapiClient->get('/posts', [
        'populate' => ['author']
    ]);
    

Integration Tips

  • Dependency Injection: Prefer constructor injection for the StrapiClientInterface.
  • Caching: Leverage Symfony’s cache system (e.g., cache:app) for frequent queries.
    # config/packages/ahc_strapi_client.yaml
    ahc_strapi_client:
        cache_enabled: true
        cache_ttl: 300 # 5 minutes
    
  • Error Handling: Wrap calls in try-catch for Ahc\StrapiClientBundle\Exception\StrapiException.
    try {
        $data = $this->strapiClient->get('/posts');
    } catch (StrapiException $e) {
        $this->addFlash('error', $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle Structure

    • The bundle is archived and lacks active maintenance. Use at your own risk.
    • Symfony 6+ Compatibility: Untested; may require patches (e.g., HttpClient updates).
  2. Configuration Quirks

    • Base URI: Must end with /api (Strapi’s default API prefix). ❌ http://example.comFailshttp://example.com/apiWorks
    • Token Authentication: Ensure the api_token is a Strapi REST API token (not JWT).
  3. Rate Limiting Strapi’s default rate limits (e.g., 100 requests/minute) may trigger 429 errors. Implement retries:

    $this->strapiClient->setRetryStrategy(new RetryStrategy(3, 100));
    
  4. Media Uploads

    • File Validation: Strapi may reject files based on its upload.config.js. Check the Strapi admin panel for allowed MIME types.
    • Field Mapping: The uploadMedia method requires explicit field names (e.g., ['field' => 'image']).

Debugging

  • Enable Debug Mode Set debug: true in config to log raw responses:

    ahc_strapi_client:
        debug: true
    

    Check var/log/dev.log for details.

  • Strapi API Logs Enable Strapi’s logging to debug 4xx/5xx errors:

    // config/env/production/server.js
    module.exports = ({ env }) => ({
        server: {
            logLevel: 'debug',
        },
    });
    

Extension Points

  1. Custom Headers Extend the client to add headers (e.g., for Strapi plugins):

    $this->strapiClient->setDefaultOption('headers', [
        'X-Custom-Header' => 'value',
    ]);
    
  2. Middleware Add request/response middleware via Symfony’s HttpClient:

    $this->strapiClient->setMiddleware([
        new MyRequestMiddleware(),
    ]);
    
  3. Event Listeners Listen for Strapi webhook events (if using Strapi’s real-time features):

    // src/EventListener/StrapiWebhookListener.php
    public function onStrapiWebhook(StrapiWebhookEvent $event) {
        // Handle real-time updates
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky