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

Common Bundle Laravel Package

anzusystems/common-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require anzusystems/common-bundle --no-scripts
    
  2. Kernel Configuration: Update public/index.php and bin/console to extend AnzuKernel with required parameters:

    return new Kernel(
        appNamespace: $context['APP_NAMESPACE'],
        appSystem: $context['APP_SYSTEM'], // e.g., "core"
        appVersion: $context['APP_VERSION'], // e.g., "1.0.0"
        appReadOnlyMode: (bool) $context['APP_READ_ONLY_MODE'],
        environment: $context['APP_ENV'],
        debug: (bool) $context['APP_DEBUG'],
    );
    
  3. Configuration: Define config/packages/anzu_common.yaml with minimal required settings (e.g., user_entity_class, app_entity_namespace).

  4. First Use Case: Leverage the health check feature by enabling it in anzu_common.yaml:

    health_check:
        enabled: true
    

    Access /health endpoint to verify system status.


Implementation Patterns

Core Workflows

1. Logging & Auditing

  • Journal Logs: Use MongoDB for structured logging (configured in logs.journal).

    logs:
        journal:
            mongo:
                uri: '%env(ANZU_MONGODB_APP_LOG_URI)%'
    

    Logs are sent via Symfony Messenger (configure messenger_transport).

  • Audit Logs: Track CRUD operations on entities (configure logs.audit.logged_methods).

    logs:
        audit:
            logged_methods: ['POST', 'PUT', 'PATCH', 'DELETE']
    

2. Permissions & Security

  • Define permissions in anzu_common.permissions.config:
    permissions:
        config:
            app_article:
                create: {}
                delete:
                    grants: [0, 1, 2]
    
  • Use AbstractVoter for role-based access control (RBAC):
    use AnzuSystems\CommonBundle\Security\Voter\AbstractVoter;
    
    class ArticleVoter extends AbstractVoter {
        protected function supports(string $attribute, mixed $subject): bool {
            return $attribute === 'EDIT' && $subject instanceof Article;
        }
    }
    

3. Health Checks

  • Extend default modules (e.g., OpCacheModule, RedisModule) or add custom ones:
    use AnzuSystems\CommonBundle\HealthCheck\Module\HealthCheckModuleInterface;
    
    class CustomHealthCheckModule implements HealthCheckModuleInterface {
        public function check(): bool { /* ... */ }
    }
    
    Register in anzu_common.health_check.modules.

4. Command Locking

  • Prevent concurrent execution of commands (e.g., ConsumeMessagesCommand is unlocked by default):
    unlocked_commands:
        - App\Command\ImportDataCommand
    

5. Value Objects & DTOs

  • Use ValueObject trait for immutable data:
    use AnzuSystems\CommonBundle\Model\ValueObject;
    
    class Email implements ValueObject {
        private string $address;
    
        public function __construct(string $address) {
            $this->address = $address;
        }
    }
    
  • Leverage UniqueEntityDto for validation:
    use AnzuSystems\CommonBundle\Dto\UniqueEntityDto;
    
    class UserDto extends UniqueEntityDto {
        public string $email;
    }
    

6. Argument Resolvers

  • Use built-in resolvers (e.g., CurrentUserResolver) in controllers:
    use AnzuSystems\CommonBundle\Controller\ArgumentResolver\CurrentUserResolver;
    
    #[Route('/profile')]
    public function profile(#[CurrentUser] User $user) { /* ... */ }
    

7. Fixtures & Testing

  • Load test data with FixturesLoader:
    use AnzuSystems\CommonBundle\Fixtures\FixturesLoader;
    
    $loader = new FixturesLoader();
    $loader->load('path/to/fixtures');
    

Integration Tips

  1. Environment Variables: Add use_putenv to composer.json for global env vars (e.g., Google SDK):

    "extra": {
        "runtime": {
            "use_putenv": true
        }
    }
    
  2. Proxy Cache: Enable HTTP cache headers:

    settings:
        app_cache_proxy_enabled: true
    
  3. Error Handling: Customize exception handlers in anzu_common.errors.exception_handlers:

    exception_handlers:
        - App\Exception\Handler\CustomValidationHandler
    
  4. Symfony Messenger: Configure transport for logs:

    logs:
        messenger_transport:
            name: 'core_log'
            dsn: '%env(MESSENGER_TRANSPORT_DSN)%?topic[name]=core_log'
    

Gotchas and Tips

Pitfalls

  1. Kernel Initialization:

    • Forgetting to pass appSystem, appVersion, and appReadOnlyMode to AnzuKernel will cause runtime errors.
    • Fix: Ensure all entry points (index.php, console) initialize AnzuKernel correctly.
  2. BC Breaks:

    • v10.0.0: anzu_mongo_app_log_collectionanzu_mongo_journal_log_collection (check routes and config).
    • v8.0.0: AbstractVoter now expects ROLE_SUPER_ADMIN (not ROLE_ADMIN) for full access.
    • v7.0.0: Job status events may not update modifiedBy if not handled properly.
  3. Permissions:

    • Default grants (default_grants) apply to all actions unless overridden. Misconfiguration can lead to unintended access.
    • Tip: Test permission logic with ROLE_SUPER_ADMIN first.
  4. Logging:

    • v10.0.0: App logger now defaults to Sentry/Syslog. Use journal for MongoDB logs.
    • Messenger Transport: Ensure MESSENGER_TRANSPORT_DSN is set in .env.
  5. Health Checks:

    • Custom modules must implement HealthCheckModuleInterface. Missing check() method will fail silently.
    • Debugging: Check DataMountModule for filesystem issues (e.g., missing directories).
  6. Concurrency:

    • Commands not in unlocked_commands are locked by default. Overlapping executions may cause deadlocks.
    • Tip: Use findByApiParamsWithInfiniteListing for paginated, concurrent-safe queries.

Debugging Tips

  1. Permission Denied:

    • Enable debug mode (debug: true in AnzuKernel) and check Symfony’s security events.
    • Command:
      bin/console debug:security
      
  2. Logging Issues:

    • Verify MongoDB connection in logs.journal.mongo and logs.audit.mongo.
    • Test Connection:
      bin/console debug:container AnzuSystems\CommonBundle\Logger\JournalLogger
      
  3. Health Check Failures:

    • Disable modules one by one in health_check.modules to isolate the issue.
    • Example:
      modules:
          - AnzuSystems\CommonBundle\HealthCheck\Module\MysqlModule
      
  4. Command Locking:

    • Check anzu_common.settings.app_redis for Redis service ID.
    • Test Lock:
      bin/console anzusystems:lock:test App\Command\MyCommand
      
  5. Value Object Validation:

    • Use UniqueEntityDto for database uniqueness checks:
      $dto = new UserDto();
      $dto->email = 'test@example.com';
      $validator = new UniqueEntityDtoValidator($dto, User::class, 'email');
      $errors = $validator->validate();
      

Extension Points

  1. Custom Exception Handlers:

    • Extend AbstractExceptionHandler:
      use AnzuSystems\CommonBundle\Exception\Handler\AbstractExceptionHandler;
      
      class CustomHandler extends AbstractExceptionHandler {
          public function handle(Throwable $exception): Response { /* ... */ }
      }
      
    • Register in anzu_common.errors.exception_handlers.
  2. Custom Health Check Modules:

    • Implement HealthCheckModuleInterface:
      class CustomModule implements HealthCheckModuleInterface {
          public function check(): bool {
              return file_exists('/custom/health/file');
          }
      }
      
    • Add to health_check.modules.
  3. Custom Argument Resolvers:

    • Extend AbstractArgumentResolver:
      use AnzuSystems\CommonBundle\Controller\ArgumentResolver\AbstractArgumentResolver;
      
      class CustomResolver extends AbstractArgumentResolver {
          public function supports(Request $request,
      
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