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

Relay Nexus Bundle Laravel Package

dbp/relay-nexus-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dbp/relay-nexus-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        DigitalBlueprint\RelayNexusBundle\DbpRelayNexusBundle::class => ['all' => true],
    ];
    
  2. Configuration Create config/packages/dbp_relay_nexus.yaml with a minimal setup:

    dbp_relay_nexus:
        topics:
            - "https://your-app.org/topic.metadata.json"
        typesense:
            api_url: "%env(NEXUS_TYPESENSE_API_URL)%"
            api_key: "%env(NEXUS_TYPESENSE_API_KEY)%"
    
  3. First Use Case

    • Fetch Topics: Use the TopicManager service to load topic metadata:
      $topicManager = $this->container->get('dbp_relay_nexus.topic_manager');
      $topics = $topicManager->getTopics();
      
    • Search Integration: Query Typesense via the TypesenseClient:
      $typesense = $this->container->get('dbp_relay_nexus.typesense_client');
      $results = $typesense->search('query', 'collection_name');
      

Implementation Patterns

Core Workflows

  1. Topic Management

    • Dynamic Loading: Topics are fetched from remote URLs on bundle initialization. Cache them in cache/ for performance:
      dbp_relay_nexus:
          topics:
              - "https://app1.org/topic.metadata.json"
              - "https://app2.org/topic.metadata.json"
          cache_topics: true  # Enable caching (default: false)
      
    • Validation: Override TopicValidator to enforce custom metadata schemas:
      // src/Service/TopicValidator.php
      class CustomTopicValidator extends TopicValidator {
          public function validate(array $metadata): bool {
              // Add custom rules
              return parent::validate($metadata);
          }
      }
      
      Register in services.yaml:
      services:
          dbp_relay_nexus.topic_validator: '@App\Service\CustomTopicValidator'
      
  2. Typesense Integration

    • Search Queries: Use the client for full-text search:
      $results = $typesense->search('laravel', 'documents', [
          'query_by' => 'title,content',
          'per_page' => 10,
      ]);
      
    • Index Management: Create/update indices dynamically:
      $typesense->createCollection('new_collection', [
          'name' => 'new_collection',
          'fields' => [
              ['name' => 'title', 'type' => 'string'],
              ['name' => 'content', 'type' => 'string'],
          ],
      ]);
      
  3. Authorization

    • Role Mapping: Extend role logic in AuthorizationManager:
      // src/Service/AuthorizationManager.php
      class CustomAuthorizationManager extends AuthorizationManager {
          protected function resolveRole(string $role): bool {
              // Custom logic (e.g., check DB, external API)
              return $role === 'ROLE_ADMIN';
          }
      }
      
    • Middleware: Protect routes with the NexusAuthenticator:
      // src/Kernel.php
      protected $middlewareAliases = [
          'nexus.auth' => \DigitalBlueprint\RelayNexusBundle\Middleware\NexusAuthenticator::class,
      ];
      
  4. Event-Driven Architecture

    • Topic Events: Listen for topic updates:
      // src/EventListener/TopicUpdateListener.php
      class TopicUpdateListener {
          public function onTopicUpdated(TopicUpdatedEvent $event) {
              // React to changes (e.g., log, notify frontend)
          }
      }
      
      Register in services.yaml:
      services:
          App\EventListener\TopicUpdateListener:
              tags:
                  - { name: 'kernel.event_listener', event: 'dbp_relay_nexus.topic.updated' }
      

Integration Tips

  1. Frontend Sync

    • Use the Nexus Frontend App as a reference for real-time updates via WebSocket or polling:
      // Example: Poll for topic changes
      setInterval(async () => {
          const response = await fetch('/api/nexus/topics');
          const topics = await response.json();
          // Update UI
      }, 30000);
      
  2. Caching Strategies

    • Cache Typesense results with Symfony Cache:
      # config/packages/cache.yaml
      framework:
          cache:
              app: cache.adapter.redis
      
      Wrap Typesense calls:
      $cache = $this->container->get('cache.app');
      $cacheKey = 'typesense:query:' . md5($query);
      $results = $cache->get($cacheKey, function() use ($typesense, $query) {
          return $typesense->search($query, 'collection');
      });
      
  3. Testing

    • Mock the TopicManager and TypesenseClient in PHPUnit:
      $this->mockBuilder()
          ->getContainer()
          ->andReturnSelf()
          ->get('dbp_relay_nexus.topic_manager')
          ->andReturn($this->createMock(TopicManager::class));
      

Gotchas and Tips

Pitfalls

  1. Topic Metadata Format

    • The bundle expects topic.metadata.json to follow a strict schema. Validate locally before deploying:
      php bin/console debug:container dbp_relay_nexus.topic_validator | grep -A5 "validate"
      
    • Common issues:
      • Missing id or name fields.
      • Invalid actions array structure (must include method and endpoint).
  2. Typesense Configuration

    • API Key Permissions: Ensure the key has search, create, and delete permissions for collections.
    • Rate Limits: Typesense may throttle requests. Implement exponential backoff:
      try {
          $results = $typesense->search($query);
      } catch (TypesenseException $e) {
          if ($e->getCode() === 429) {
              sleep(2 ** $attempt++);
              retry();
          }
          throw $e;
      }
      
  3. Authorization Quirks

    • Role Resolution Order: The bundle checks roles in the order defined in dbp_relay_nexus.yaml. Override AuthorizationManager::resolveRoles() to customize:
      public function resolveRoles(UserInterface $user): array {
          $roles = parent::resolveRoles($user);
          // Add dynamic roles (e.g., from DB)
          $roles[] = 'ROLE_' . strtoupper($user->getDepartment());
          return array_unique($roles);
      }
      
    • Circular Dependencies: Avoid circular role checks (e.g., ROLE_USER depends on ROLE_DEVELOPER which depends on ROLE_USER).
  4. Performance

    • Topic Loading: Fetching topics synchronously blocks requests. Use cache_topics: true and preload in a command:
      // src/Command/PreloadTopicsCommand.php
      class PreloadTopicsCommand extends Command {
          protected function execute(InputInterface $input, OutputInterface $output) {
              $topicManager = $this->getContainer()->get('dbp_relay_nexus.topic_manager');
              $topicManager->preloadTopics();
              $output->writeln('Topics preloaded!');
          }
      }
      
      Register as a cron job:
      * * * * * php bin/console app:preload-topics
      

Debugging

  1. Enable Debug Mode Add to config/packages/dev/dbp_relay_nexus.yaml:

    dbp_relay_nexus:
        debug: true
    
    • Logs topic loading errors to var/log/dev.log.
    • Dumps Typesense queries in var/log/debug.log.
  2. Common Errors

    Error Solution
    TopicNotFoundException Verify topic URLs in dbp_relay_nexus.yaml and network connectivity.
    TypesenseConnectionException Check NEXUS_TYPESENSE_API_URL and key permissions.
    AuthorizationException Debug role resolution with var_dump($this->get('security.token_storage')->getToken()->getRoles()).
  3. Extension Points

    • Custom Topic Sources: Implement TopicSourceInterface for non-HTTP sources (e.g., database):
      class DatabaseTopicSource implements TopicSourceInterface {
          public function getTopics(): array {
              return $this->
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware