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

Foursquare Bundle Laravel Package

ddnet/foursquare-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ner0tic/foursquare-bundle
    

    Add the bundle to config/bundles.php:

    Ner0tic\FoursquareBundle\Ner0ticFoursquareBundle::class => ['all' => true],
    
  2. Configuration: Publish the default config:

    php bin/console ner0tic:foursquare:install
    

    Update config/packages/ner0tic_foursquare.yaml with your Foursquare API credentials (client ID, secret, and OAuth redirect URI).

  3. First Use Case: Fetch a venue by ID in a controller:

    use Ner0tic\FoursquareBundle\Service\VenueService;
    
    class VenueController extends AbstractController
    {
        public function show(VenueService $venueService, string $venueId)
        {
            $venue = $venueService->getVenue($venueId);
            return $this->json($venue);
        }
    }
    

Implementation Patterns

Core Workflows

  1. OAuth Integration:

    • Use the ConnectController (auto-generated via ner0tic:foursquare:install) for user authentication.
    • Redirect users to Foursquare for OAuth:
      return $this->redirect($this->container->get('ner0tic_foursquare.oauth')->getAuthorizationUrl());
      
    • Handle callback in connectCallback action to exchange code for an access token.
  2. Service Layer Abstraction:

    • Inject services (e.g., UserService, VenueService) into controllers or services:
      public function __construct(
          private UserService $userService,
          private CheckinService $checkinService
      ) {}
      
    • Chain operations (e.g., fetch user checkins for a venue):
      $checkins = $checkinService->getCheckinsForVenue($venueId, $limit = 10);
      
  3. Entity Mapping:

    • The bundle maps Foursquare API responses to Symfony entities (e.g., User, Venue). Extend or override these in your project:
      # config/packages/ner0tic_foursquare.yaml
      ner0tic_foursquare:
          entities:
              user: App\Entity\CustomUser
              venue: App\Entity\CustomVenue
      
  4. Pagination:

    • Use getPaginatedResults() methods (e.g., getVenues()) to handle large datasets:
      $venues = $venueService->getVenues(['near' => 'San Francisco'], 20);
      
  5. Event Handling:

    • Subscribe to Foursquare events (e.g., foursquare.user.connected) in your EventSubscriber:
      public static function getSubscribedEvents()
      {
          return [
              'foursquare.user.connected' => 'onUserConnected',
          ];
      }
      

Integration Tips

  1. Caching:

    • Enable caching for API responses in config/packages/ner0tic_foursquare.yaml:
      ner0tic_foursquare:
          cache_enabled: true
          cache_lifetime: 3600  # 1 hour
      
  2. Error Handling:

    • Wrap API calls in try-catch blocks to handle FoursquareApiException:
      try {
          $venue = $venueService->getVenue($venueId);
      } catch (FoursquareApiException $e) {
          $this->addFlash('error', $e->getMessage());
          return $this->redirectToRoute('home');
      }
      
  3. Testing:

    • Use the FoursquareClientMock for unit tests:
      $mockClient = $this->createMock(FoursquareClient::class);
      $mockClient->method('get')->willReturn(['response' => 'data']);
      $this->container->set('ner0tic_foursquare.client', $mockClient);
      
  4. Custom Endpoints:

    • Extend the FoursquareClient to add custom API calls:
      class CustomFoursquareClient extends FoursquareClient
      {
          public function getCustomData($params)
          {
              return $this->get('/custom/endpoint', $params);
          }
      }
      
      Register it as a service:
      services:
          App\Service\CustomFoursquareClient:
              decorates: ner0tic_foursquare.client
              arguments: ['@App\Service\CustomFoursquareClient.inner']
      

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle:

    • The original ddnet/foursquare-bundle is deprecated. Use ner0tic/foursquare-bundle (linked in the README). Ensure you’re not mixing dependencies.
  2. OAuth Redirect URI:

    • The redirect URI must match exactly what’s registered in your Foursquare developer account. Test locally with http://localhost:8000/connect/callback and update for production.
  3. Rate Limiting:

    • Foursquare enforces rate limits. Cache aggressively and implement exponential backoff in custom clients:
      try {
          $response = $client->get('/venues/search', $params);
      } catch (RateLimitExceededException $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      
  4. Entity Overrides:

    • If you override entities (e.g., CustomUser), ensure all required fields from Foursquare’s response are mapped. Use Serializer annotations or Hydrator for complex cases.
  5. Token Expiry:

    • Access tokens expire (~30 days). Implement token refresh logic in your ConnectController or use a library like league/oauth2-client for advanced handling.

Debugging

  1. API Logs:

    • Enable debug mode in config/packages/ner0tic_foursquare.yaml:
      ner0tic_foursquare:
          debug: true
      
    • Logs will appear in var/log/dev.log.
  2. Common Errors:

    • Invalid OAuth token: Token expired or revoked. Redirect users to re-authenticate.
    • Endpoint not found: Verify the endpoint exists in Foursquare’s API docs.
    • Missing required parameter: Check $params for required fields (e.g., v=20230601 for versioning).
  3. Symfony Profiler:

    • Use the profiler to inspect Foursquare API calls and response times under Profiler > HTTP > Foursquare.

Extension Points

  1. Custom Services:

    • Create a service to combine multiple API calls (e.g., "Get venue + recent checkins"):
      class VenueDashboardService
      {
          public function __construct(
              private VenueService $venueService,
              private CheckinService $checkinService
          ) {}
      
          public function getDashboardData($venueId)
          {
              return [
                  'venue' => $this->venueService->getVenue($venueId),
                  'checkins' => $this->checkinService->getRecentCheckins($venueId),
              ];
          }
      }
      
  2. Webhook Integration:

    • Foursquare supports webhooks for real-time updates. Extend the bundle by adding a WebhookController:
      public function handleWebhook(Request $request)
      {
          $payload = json_decode($request->getContent(), true);
          $this->dispatchEvent('foursquare.webhook.received', $payload);
      }
      
  3. Geocoding:

    • Combine with Symfony’s GeocoderBundle to convert addresses to Foursquare venues:
      $geocoder = $this->container->get('geocoder');
      $coordinates = $geocoder->geocode('123 Main St, San Francisco');
      $venues = $venueService->getVenues(['near' => $coordinates->getLatitude().','.$coordinates->getLongitude()]);
      
  4. Background Jobs:

    • Offload heavy operations (e.g., syncing user checkins) to a queue (e.g., Symfony Messenger):
      $this->messageBus->dispatch(new SyncUserCheckinsMessage($userId));
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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