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

Campusonline Api Laravel Package

dbp/campusonline-api

PHP client for CAMPUSonline web services. Supports legacy REST endpoints, generic exports API, and legacy XML web services. Configure base URL and credentials/token, then access resources like UCard, exports, and organization units.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require dbp/campusonline-api

Ensure your Laravel project meets the package's PHP version requirements (8.2+).

  1. First API Call:

    use Dbp\CampusonlineApi\Rest\Api;
    
    $api = new Api(
        env('CAMPUSONLINE_BASE_URL', 'https://qline.example.at/online/'),
        env('CAMPUSONLINE_CLIENT_ID'),
        env('CAMPUSONLINE_CLIENT_SECRET')
    );
    

    Store credentials in .env:

    CAMPUSONLINE_BASE_URL=https://your-instance.at/online/
    CAMPUSONLINE_CLIENT_ID=your_client_id
    CAMPUSONLINE_CLIENT_SECRET=your_client_secret
    
  2. First Use Case: Fetch a student's UCard data (e.g., for authentication):

    $ucard = $api->UCard();
    $cardData = $ucard->getCardsForIdentIdObfuscated('1234567890');
    

Implementation Patterns

Core Workflows

  1. Authentication Flow:

    • Use Api constructor with OAuth2 credentials.
    • For legacy XML APIs, pass an api_token instead of client credentials.
  2. Resource Fetching:

    • REST APIs (modern):
      $users = $api->User()->getUsers(['filter' => ['status' => 'active']]);
      
    • Generic Exports (custom endpoints):
      $export = $api->GenericApi('loc_apiMyExport');
      $data = $export->getResource('ID', '42', ['language' => 'en']);
      
    • Legacy XML Web Services:
      $org = $api->OrganizationUnit();
      $unit = $org->getOrganizationUnitById('1234');
      
  3. Pagination:

    • Use offset/limit for REST APIs:
      $users = $api->User()->getUsers(['offset' => 0, 'limit' => 100]);
      
    • For cursor-based pagination (e.g., Public REST APIs), leverage the built-in support:
      $courses = $api->Course()->getCourses(['cursor' => 'initial']);
      do {
          $courses = $api->Course()->getCourses(['cursor' => $courses->getNextCursor()]);
      } while ($courses->hasNext());
      
  4. Filtering:

    • Use FilterBuilder for complex queries:
      use Dbp\CampusonlineApi\FilterBuilder;
      
      $filter = (new FilterBuilder())
          ->equals('status', 'active')
          ->contains('name', 'Smith');
      
      $users = $api->User()->getUsers(['filter' => $filter->build()]);
      
    • For substring searches (e.g., autocomplete):
      $validSubstrings = FilterBuilder::extractValidFilterSubstrings(
          $userInput,
          ['name', 'email']
      );
      
  5. Caching:

    • Enable Guzzle cache middleware (recommended for performance):
      $api = new Api(
          $baseUrl,
          $clientId,
          $clientSecret,
          [
              'cache' => [
                  'enabled' => true,
                  'middleware' => new \kevinrob\GuzzleCacheMiddleware\CacheMiddleware(
                      new \kevinrob\GuzzleCacheMiddleware\Storage\Psr6CacheStorage(
                          new \Symfony\Component\Cache\Adapter\FilesystemAdapter()
                      )
                  ),
              ],
          ]
      );
      
    • Force cache misses (e.g., for testing):
      $data = $api->User()->getUsers(['force_cache_miss' => true]);
      
  6. Error Handling:

    • Wrap API calls in try-catch blocks:
      try {
          $data = $api->User()->getUserByPersonUid('12345');
      } catch (\Dbp\CampusonlineApi\ApiException $e) {
          Log::error('Campusonline API error: ' . $e->getMessage());
          return response()->json(['error' => 'Service unavailable'], 503);
      }
      

Integration Tips

  • Laravel Service Providers: Bind the API client to the container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Api::class, function ($app) {
            return new Api(
                config('campusonline.base_url'),
                config('campusonline.client_id'),
                config('campusonline.client_secret')
            );
        });
    }
    

    Configure in config/campusonline.php:

    return [
        'base_url' => env('CAMPUSONLINE_BASE_URL'),
        'client_id' => env('CAMPUSONLINE_CLIENT_ID'),
        'client_secret' => env('CAMPUSONLINE_CLIENT_SECRET'),
        'cache' => [
            'enabled' => env('CAMPUSONLINE_CACHE_ENABLED', false),
        ],
    ];
    
  • Queued Jobs: Offload heavy API calls to queues (e.g., fetching large datasets):

    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class SyncCampusonlineData implements ShouldQueue
    {
        use Queueable;
    
        public function handle(Api $api)
        {
            $data = $api->GenericApi('loc_apiLargeExport')->getResource('ID', '123');
            // Process data...
        }
    }
    
  • API Rate Limiting: Implement middleware to throttle requests:

    // app/Http/Middleware/ThrottleCampusonline.php
    public function handle($request, Closure $next)
    {
        return $next($request)->throttle([
            'campusonline' => ['max' => 60, 'perMinute'],
        ]);
    }
    

Gotchas and Tips

Common Pitfalls

  1. Authentication Issues:

    • Error: 401 Unauthorized or invalid_grant.
    • Cause: Expired tokens or incorrect credentials.
    • Fix:
      • Ensure client_id/client_secret are correct (check .env).
      • Use checkConnection() to validate the API instance:
        if (!$api->User()->checkConnection()) {
            throw new \RuntimeException('Campusonline API unavailable');
        }
        
      • For Public REST APIs, refresh tokens proactively (v0.3.33+):
        $api->PublicRest()->refreshToken();
        
  2. Pagination Edge Cases:

    • Error: Infinite loops with cursor-based pagination.
    • Cause: Missing hasNext() check or malformed cursors.
    • Fix: Always validate cursors:
      if (!$courses->hasNext()) break;
      
  3. Filtering Quirks:

    • Error: 500 Internal Server Error with complex filters.
    • Cause: Invalid filter syntax or unsupported fields.
    • Fix:
      • Use FilterBuilder for safe construction.
      • Test filters incrementally (e.g., start with simple equals).
      • Check the CAMPUSonline API docs for supported fields.
  4. Legacy XML APIs:

    • Error: XML parsing warnings or malformed responses.
    • Cause: Invalid XML from CAMPUSonline or unsupported attributes.
    • Fix:
      • Suppress warnings with libxml_use_internal_errors(true) if needed.
      • Use getOrganizationUnitsById() for batch fetching (more efficient than looping).
  5. Caching Gotchas:

    • Issue: Stale data due to cache.
    • Fix:
      • Use force_cache_miss for critical updates.
      • Set short TTLs for volatile data (e.g., user sessions):
        $cacheMiddleware->setCacheTTL(300); // 5 minutes
        
  6. POST vs. GET:

    • Issue: Large payloads failing with GET (URL length limits).
    • Fix: Force POST for large exports:
      $data = $api->GenericApi('loc_apiLargeExport')->getResource(
          'ID', '123',
          ['method' => 'POST']
      );
      

Debugging Tips

  1. Enable Guzzle Debugging: Add a debug handler to Guzzle for verbose logging:

    $api = new Api($baseUrl, $clientId, $clientSecret, [
        'handler' => \GuzzleHttp\HandlerStack::create(new \GuzzleHttp\Handler\CurlHandler()),
        'debug' => true,
    ]);
    
  2. Inspect Raw Responses: Use getLastResponse() to debug API calls:

    try {
        $data = $api->
    
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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin