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

Photo Rest Bundle Laravel Package

antwebes/photo-rest-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require antwebes/photo-rest-bundle
    

    Add the bundle to AppKernel.php (Symfony 2.x):

    new Antwebes\PhotoRestBundle\AntwebesPhotoRestBundle(),
    
  2. Configuration: Enable the bundle in config.yml:

    antwebes_photo_rest:
        # Optional: Customize upload directory (default: %kernel.root_dir%/../web/uploads/photos)
        upload_dir: "%kernel.root_dir%/../web/uploads/custom_photos"
    
  3. First Use Case:

    • Upload a Photo: Use the PhotoController (auto-generated by the bundle) to handle uploads via a form with enctype="multipart/form-data". Example route (check routing.yml for defaults):

      photo_upload:
          path:     /api/photos/upload
          defaults: { _controller: AntwebesPhotoRestBundle:Photo:upload }
      
    • Fetch Photos: Access photos via REST endpoints (e.g., /api/photos). The bundle provides basic CRUD operations out-of-the-box.


Implementation Patterns

Core Workflows

  1. Photo Management:

    • Upload: Submit a file to /api/photos/upload. The bundle handles storage in the configured upload_dir and associates metadata (e.g., user_id, created_at).
    • Retrieve: Fetch photos via /api/photos (supports pagination, filtering by user_id, or date ranges). Example API call:
      curl -X GET "/api/photos?user_id=1&start_date=2015-01-01"
      
    • Vote System: Use /api/photos/{id}/vote to increment a photo’s vote count (restricted to one vote per user per photo). Example:
      curl -X POST "/api/photos/123/vote"
      
  2. Entity Integration:

    • Extend the Photo entity (Antwebes\PhotoRestBundle\Entity\Photo) to add custom fields:
      // src/Acme/YourBundle/Entity/CustomPhoto.php
      use Antwebes\PhotoRestBundle\Entity\Photo as BasePhoto;
      
      class CustomPhoto extends BasePhoto {
          /**
           * @ORM\Column(type="string", length=255)
           */
          private $customField;
      }
      
    • Override the bundle’s PhotoRepository to add custom queries (e.g., for date-range votes):
      public function getVotesByDateRange(\DateTime $start, \DateTime $end) {
          return $this->createQueryBuilder('p')
              ->where('p.createdAt BETWEEN :start AND :end')
              ->setParameter('start', $start)
              ->setParameter('end', $end)
              ->getQuery()
              ->getResult();
      }
      
  3. Transformer Patterns:

    • Use the IdToPhotoTransformer (hotfix in v0.1.2) to convert IDs to Photo objects in controllers:
      $transformer = $this->get('antwebes_photo_rest.id_to_photo_transformer');
      $photo = $transformer->transform(123); // Returns Photo entity for ID 123
      
  4. Security:

    • Restrict vote actions to authenticated users. Override the voteAction in a custom controller or use Symfony’s security voters:
      # security.yml
      access_control:
          - { path: ^/api/photos/\d+/vote, roles: ROLE_USER }
      

Gotchas and Tips

Common Pitfalls

  1. Doctrine ORM Version:

    • The bundle requires Doctrine ORM >=2.2.3,<2.5-dev. Conflicts may arise with newer Symfony/Laravel (4.x+) or Doctrine 2.6+. Workaround:
      • Downgrade Doctrine ORM in composer.json or use a wrapper library to abstract the ORM.
      • Note: This bundle is Symfony 2.x-specific. For Laravel, consider alternatives like spatie/laravel-medialibrary.
  2. File Uploads:

    • Permissions: Ensure the upload_dir is writable by the web server (e.g., chmod -R 775 uploads).
    • Validation: The bundle lacks built-in file validation (e.g., MIME types, size). Add validation in a custom controller:
      public function uploadAction(Request $request) {
          $file = $request->files->get('photo');
          if (!$file->isValid()) {
              throw new \RuntimeException('Invalid file upload.');
          }
          if ($file->getClientOriginalExtension() !== 'jpg') {
              throw new \RuntimeException('Only JPG files allowed.');
          }
          // Proceed with bundle logic...
      }
      
  3. Vote Logic:

    • The "one user cannot vote for another" rule (v0.1.2) is enforced via business logic in the repository. Debugging:
      • Check for duplicate votes in the database if votes disappear unexpectedly.
      • Override the vote method to log issues:
        public function vote(Photo $photo, User $user) {
            if ($this->hasVoted($photo, $user)) {
                throw new \RuntimeException("User {$user->getId()} already voted.");
            }
            // ... rest of logic
        }
        
  4. Deprecation Risks:

    • Last Release: 2015. The bundle is abandoned and may break with modern Symfony/Laravel. Mitigations:
      • Fork the repository and update dependencies (e.g., Symfony 3/4, Doctrine 2.6+).
      • Replace with a maintained alternative (e.g., VichUploaderBundle for Symfony or Laravel’s built-in file uploads).

Pro Tips

  1. Custom Endpoints:

    • Extend the bundle’s routing by creating a custom controller and service:
      # services.yml
      acme.photo_custom_controller:
          class: Acme\YourBundle\Controller\CustomPhotoController
          arguments: ["@antwebes_photo_rest.photo_repository"]
          tags: ["controller.service_arguments"]
      
      // src/Acme/YourBundle/Controller/CustomPhotoController.php
      class CustomPhotoController extends Controller {
          public function getPhotosByTagAction($tag) {
              $photos = $this->get('antwebes_photo_rest.photo_repository')->findBy(['tag' => $tag]);
              return $this->json($photos);
          }
      }
      
  2. Testing:

    • Mock the PhotoRepository in unit tests to avoid file system dependencies:
      $repository = $this->createMock(PhotoRepository::class);
      $repository->method('findBy')->willReturn([$mockPhoto]);
      $this->container->set('antwebes_photo_rest.photo_repository', $repository);
      
  3. Performance:

    • For large photo collections, add database indexes to user_id and created_at in the photo table:
      // src/Acme/YourBundle/Resources/doc/doctrine/Photo.orm.yml
      Antwebes\PhotoRestBundle\Entity\Photo:
          indexes:
              user_idx: { columns: [user_id] }
              date_idx: { columns: [created_at] }
      
  4. Laravel Adaptation:

    • If migrating to Laravel, port the Photo entity and repository logic, but replace Symfony-specific components (e.g., controllers, routing) with Laravel’s equivalents. Use Laravel’s Storage facade for file handling.
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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