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

Dark Sky Api Laravel Package

dmitry-ivanov/dark-sky-api

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dmitry-ivanov/dark-sky-api
    

    Add to config/services.php (if not using Laravel's built-in service binding):

    'dark-sky' => [
        'api_key' => env('DARK_SKY_API_KEY'),
    ],
    
  2. First Use Case: Fetch Current Weather

    use DmitryIvanov\DarkSkyApi\DarkSkyApi;
    
    $api = new DarkSkyApi(config('services.dark-sky.api_key'));
    $response = $api->getCurrentWeather(37.8267, -122.4233); // Latitude, Longitude
    $data = $response->getData();
    
  3. Key Files to Review

    • src/DarkSkyApi.php (Main class)
    • src/Exceptions/ (Error handling)
    • tests/ (Usage examples)

Implementation Patterns

Core Workflows

  1. Service Provider Binding (Laravel)

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(DarkSkyApi::class, function ($app) {
            return new DarkSkyApi(config('services.dark-sky.api_key'));
        });
    }
    

    Now inject DarkSkyApi via constructor.

  2. Common API Calls

    // Current weather
    $api->getCurrentWeather($lat, $lon);
    
    // Forecast
    $api->getForecast($lat, $lon, 'hourly'); // 'hourly', 'daily', or 'minutely'
    
    // Time Machine (historical data)
    $api->getTimeMachine($lat, $lon, '2023-01-01T00:00:00');
    
  3. Response Handling

    try {
        $response = $api->getForecast($lat, $lon, 'daily');
        $data = $response->getData(); // Raw array
        $temperature = $data['daily']['data'][0]['temperatureMax'];
    } catch (DarkSkyApiException $e) {
        // Handle errors (e.g., rate limits, invalid API key)
    }
    
  4. Caching Responses (Laravel)

    // Cache for 1 hour
    $cached = Cache::remember("darksky_{$lat}_{$lon}", now()->addHours(1), function () use ($api, $lat, $lon) {
        return $api->getCurrentWeather($lat, $lon)->getData();
    });
    

Integration Tips

  • Environment Variables: Store DARK_SKY_API_KEY in .env.
  • Queue Jobs: Offload API calls to queues for long-running forecasts.
  • Model Observers: Trigger API calls on model events (e.g., saved for location models).
    // app/Observers/LocationObserver.php
    public function saved(Location $location)
    {
        $weather = app(DarkSkyApi::class)->getCurrentWeather($location->lat, $location->lon);
        $location->weather_data = $weather->getData();
        $location->save();
    }
    

Gotchas and Tips

Pitfalls

  1. Rate Limits

    • Dark Sky enforces strict rate limits.
    • Fix: Cache responses aggressively or implement exponential backoff.
      if ($api->isRateLimited()) {
          sleep($api->getRetryAfter());
      }
      
  2. Deprecated Endpoints

    • The package is archived (last release: 2022-03-12). Dark Sky’s API was shut down in 2021 (replaced by Open-Meteo).
    • Workaround: Fork the repo and update endpoints to Open-Meteo or another provider.
  3. Error Handling

    • Always wrap calls in try-catch:
      try {
          $api->getForecast(...);
      } catch (DarkSkyApiException $e) {
          Log::error("Dark Sky API Error: " . $e->getMessage());
          // Fallback to cached data or default values
      }
      
  4. Geocoding

    • The package does not include geocoding (converting addresses to coordinates).
    • Solution: Use Laravel Geocoder or Google Maps API first, then pass coords to this package.

Debugging Tips

  • Enable Debug Mode:
    $api = new DarkSkyApi($apiKey, [
        'debug' => true, // Logs raw HTTP requests/responses
    ]);
    
  • Check HTTP Status Codes:
    $response = $api->getCurrentWeather(...);
    if ($response->getStatusCode() === 429) {
        // Rate limited
    }
    

Extension Points

  1. Custom Responses Override DmitryIvanov\DarkSkyApi\Response to transform data:

    class CustomResponse extends Response
    {
        public function getFormattedData()
        {
            return [
                'temp' => $this->getData()['currently']['temperature'],
                'summary' => $this->getData()['currently']['summary'],
            ];
        }
    }
    
  2. Add New Endpoints Extend DarkSkyApi to support unsupported endpoints (e.g., alerts):

    class ExtendedDarkSkyApi extends DarkSkyApi
    {
        public function getAlerts($lat, $lon)
        {
            return $this->request('GET', "/{$lat},{$lon}/alerts");
        }
    }
    
  3. Mocking for Tests Use Laravel’s HTTP mocking or create a decorator:

    $mockApi = new class($apiKey) extends DarkSkyApi {
        public function getCurrentWeather(...$args)
        {
            return new Response(200, ['currently' => ['temperature' => 20]]);
        }
    };
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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