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

Woohoolabs Yin Bundle Laravel Package

divante-ltd/woohoolabs-yin-bundle

Symfony 3.3 bundle integrating woohoolabs/yin to help you build JSON:API-compliant endpoints quickly. Install via Composer and register in AppKernel to start using Yin within your Symfony application.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require divante-ltd/woohoolabs-yin-bundle
    

    Ensure your project uses Symfony 3.3 (compatibility requirement).

  2. Register the Bundle Add to app/AppKernel.php:

    new Divante\WoohoolabsYinBundle\DivanteWoohoolabsYinBundle(),
    
  3. First Use Case: Basic JSON:API Endpoint Create a resource class (e.g., src/AppBundle/Resources/Yin/Post.php):

    namespace AppBundle\Resources\Yin;
    
    use Woohoolabs\Yin\Resource\AbstractResource;
    
    class Post extends AbstractResource
    {
        protected $idAttribute = 'id';
        protected $type = 'posts';
        protected $collectionType = 'posts';
    }
    

    Register the resource in config.yml:

    divante_woohoolabs_yin:
        resources:
            - AppBundle\Resources\Yin\Post
    
  4. Test the Endpoint Access /api/posts to fetch resources in JSON:API format.


Implementation Patterns

Core Workflows

  1. Resource Definition Extend AbstractResource to define:

    • $idAttribute: Primary key (e.g., id, uuid).
    • $type: Singular resource type (e.g., posts).
    • $collectionType: Plural type for collections.
    • $attributes: Whitelist allowed fields (e.g., ['title', 'content']).
    • $relationships: Define relationships (e.g., ['author']).

    Example with relationships:

    class Post extends AbstractResource
    {
        protected $relationships = [
            'author' => [
                'resource' => 'users',
                'type' => 'belongs_to',
            ],
        ];
    }
    
  2. Customizing Serialization Override serialize() to modify output:

    public function serialize($resource)
    {
        $data = parent::serialize($resource);
        $data['custom_field'] = $resource->getCustomField();
        return $data;
    }
    
  3. Filtering & Sorting Use query parameters:

    • ?filter[title][contains]=test (filter by title).
    • ?sort=-created_at (sort descending by created_at).

    Override applyFilters() or applySorting() in your resource class for custom logic.

  4. Pagination Enable via config:

    divante_woohoolabs_yin:
        pagination:
            enabled: true
            limit: 20
    

    Use ?page[number]=2&page[size]=10 for pagination.

  5. Integration with Doctrine Use Woohoolabs\Yin\Resource\DoctrineResource for ORM support:

    class Post extends DoctrineResource
    {
        protected $entityClass = 'AppBundle\Entity\Post';
    }
    
  6. Authentication & Authorization Integrate with Symfony’s security system by extending Woohoolabs\Yin\Resource\AbstractResource and overriding:

    public function getAccessControl()
    {
        return new AccessControl(
            new AllowIfGranted('ROLE_USER'),
            new DenyIfNotGranted('ROLE_ADMIN')
        );
    }
    

Integration Tips

  1. Symfony Routing Customize routes in routing.yml:

    divante_woohoolabs_yin:
        resource: "@DivanteWoohoolabsYinBundle/Resources/config/routing.yml"
        prefix: /api
    
  2. CORS Configuration Add to config.yml:

    nelmio_cors:
        defaults:
            allow_origin: ["*"]
            allow_methods: ["GET", "POST", "PUT", "PATCH", "DELETE"]
            allow_headers: ["content-type", "authorization"]
            max_age: 3600
    
  3. Documentation with NelmioApiDoc Annotate resources for Swagger/OpenAPI:

    /**
     * @ApiResource(
     *     collectionOperations={
     *         "get"={"method"="GET"},
     *         "post"={"method"="POST"}
     *     },
     *     itemOperations={
     *         "get"={"method"="GET"},
     *         "put"={"method"="PUT"},
     *         "delete"={"method"="DELETE"}
     *     }
     * )
     */
    class Post extends AbstractResource { ... }
    
  4. Event Listeners Subscribe to Yin events (e.g., yin.resource.pre_serialize) for pre/post-processing:

    // src/AppBundle/EventListener/YinListener.php
    public function onPreSerialize(ResourceEvent $event)
    {
        $resource = $event->getResource();
        // Modify $resource data here
    }
    

    Register in services.yml:

    services:
        app.yin_listener:
            class: AppBundle\EventListener\YinListener
            tags:
                - { name: kernel.event_listener, event: yin.resource.pre_serialize, method: onPreSerialize }
    

Gotchas and Tips

Pitfalls

  1. Symfony 3.3 Dependency

    • Issue: Bundle requires Symfony 3.3. Using Symfony 4+ may break compatibility.
    • Fix: Use a compatibility layer (e.g., symfony/symfony:3.4.*) or fork the bundle.
  2. Missing Documentation

    • Issue: Limited official docs; rely on woohoolabs/yin for core concepts.
    • Fix: Study the Yin framework docs and inspect DivanteWoohoolabsYinBundle tests.
  3. Relationship Loading

    • Issue: Eager-loading relationships may cause N+1 queries.
    • Fix: Use fetch() with loadRelationships():
      $post = $this->fetch($id, ['author']);
      
  4. Caching Headers

    • Issue: Default pagination may lack Link headers for navigation.
    • Fix: Extend the bundle’s pagination logic or use a middleware to add headers.
  5. Error Handling

    • Issue: Custom errors may not serialize as JSON:API-compliant errors.
    • Fix: Override createErrorResponse() in your resource:
      protected function createErrorResponse($status, $message, $errors = [])
      {
          return new JsonApiResponse($status, [
              'errors' => [
                  [
                      'title' => $message,
                      'detail' => $errors,
                      'code' => 'custom_error',
                  ],
              ],
          ]);
      }
      

Debugging Tips

  1. Enable Debug Mode Set divante_woohoolabs_yin.debug: true in config to log SQL queries and requests.

  2. Check Request/Response Use Symfony’s profiler (/_profiler) to inspect Yin requests/responses.

  3. Validate JSON:API Compliance Use tools like jsonapi.io to validate responses.

  4. Common Errors

    • 404 Not Found: Ensure $idAttribute matches your entity’s primary key.
    • 500 Server Error: Check for missing EntityManager or invalid Doctrine mappings.
    • Circular References: Use serialize() to break cycles (e.g., parent-child loops).

Extension Points

  1. Custom Serializers Implement Woohoolabs\Yin\Serializer\SerializerInterface for custom data transformation.

  2. Middleware Add middleware to the Yin stack (e.g., for logging or auth):

    divante_woohoolabs_yin:
        middleware:
            - app.yin_middleware
    
  3. Event Dispatcher Extend Yin’s event system (e.g., yin.resource.post_fetch) for post-processing.

  4. Testing Use YinTestCase for unit/integration tests:

    use Woohoolabs\Yin\Test\YinTestCase;
    
    class PostTest extends YinTestCase
    {
        public function testGetPosts()
        {
            $client = static::createClient();
            $client->request('GET', '/api/posts');
            $this->assertTrue($client->getResponse()->isSuccessful());
        }
    }
    
  5. Performance Optimization

    • Batch Loading: Use Repository::findBy() with DISTINCT for large datasets.
    • Caching: Implement Symfony\Component\HttpFoundation\ResponseCache for responses.
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope