Weave 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

Core Laravel Package

companyos/core

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require companyos/core
    

    Ensure your config/bundles.php includes:

    return [
        // ...
        CompanyOS\CoreBundle\CompanyOSCoreBundle::class => ['all' => true],
    ];
    
  2. Database Configuration Update config/packages/doctrine.yaml to match your database schema. The bundle expects DDD-style entities (e.g., src/Entity/).

  3. First Use Case: Plugin Registration Create a basic plugin in src/Plugin/ (e.g., MyPlugin.php):

    namespace App\Plugin;
    
    use CompanyOS\CoreBundle\Plugin\AbstractPlugin;
    
    class MyPlugin extends AbstractPlugin
    {
        public function getName(): string
        {
            return 'my_plugin';
        }
    }
    

    Register it in config/packages/companyos_core.yaml:

    companyos_core:
        plugins:
            my_plugin: App\Plugin\MyPlugin
    
  4. API Endpoint The bundle provides a skeleton for API routes. Extend src/Controller/ with a custom controller (e.g., ApiController.php):

    use Symfony\Component\HttpFoundation\JsonResponse;
    use Symfony\Component\Routing\Annotation\Route;
    
    class ApiController
    {
        #[Route('/api/test', name: 'api_test', methods: ['GET'])]
        public function test(): JsonResponse
        {
            return new JsonResponse(['status' => 'ok']);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Domain-Driven Design (DDD) Layering

    • Domain Layer: Define entities (e.g., User, Role) in src/Entity/ with business logic in methods.
    • Application Layer: Use services (e.g., UserService) to orchestrate domain logic. Example:
      namespace App\Service;
      
      use CompanyOS\CoreBundle\Domain\Service\UserServiceInterface;
      
      class UserService implements UserServiceInterface
      {
          public function createUser(array $data): void
          {
              // Business logic here
          }
      }
      
    • Infrastructure Layer: Configure Doctrine repositories and event listeners in config/packages/doctrine.yaml.
  2. Event-Driven Architecture

    • Dispatch domain events (e.g., UserCreatedEvent) via the event dispatcher:
      $this->eventDispatcher->dispatch(new UserCreatedEvent($user));
      
    • Listen to events in plugins or services:
      $eventDispatcher->addListener(UserCreatedEvent::class, function (UserCreatedEvent $event) {
          // Handle event (e.g., log, notify)
      });
      
  3. Plugin System Integration

    • Extend Core Functionality: Override or extend core services by implementing interfaces (e.g., UserServiceInterface).
    • Hook into Events: Plugins can subscribe to events (e.g., PluginInitializedEvent) to inject behavior:
      $eventDispatcher->addListener(PluginInitializedEvent::class, [$this, 'onPluginInit']);
      
    • Dynamic Loading: Plugins are auto-loaded via the companyos_core.plugins config. Use PluginManager to interact with them:
      $pluginManager = $this->container->get('companyos_core.plugin_manager');
      $myPlugin = $pluginManager->getPlugin('my_plugin');
      
  4. API-First Design

    • Controllers: Use Symfony’s JsonResponse for API endpoints. Leverage DTOs (Data Transfer Objects) for input/output:
      #[Route('/api/users', name: 'api_users', methods: ['POST'])]
      public function createUser(UserDto $dto): JsonResponse
      {
          $this->userService->createUser($dto->toArray());
          return new JsonResponse(['status' => 'created']);
      }
      
    • API Resources: Group related endpoints under /api/ and version them (e.g., /api/v1/users).
  5. Authentication

    • Configure OAuth2 in config/packages/security.yaml:
      security:
          providers:
              oauth_provider:
                  companyos_core:
                      service: App\Security\OAuthUserProvider
          firewalls:
              api:
                  pattern: ^/api
                  stateless: true
                  oauth:
                      provider: oauth_provider
      
    • Implement OAuthUserProvider to fetch users from your domain layer.

Integration Tips

  1. Doctrine Entities

    • Ensure entities extend CompanyOS\CoreBundle\Domain\Entity\AbstractEntity for base functionality (e.g., timestamps, UUIDs).
    • Use repositories to abstract database operations:
      namespace App\Repository;
      
      use CompanyOS\CoreBundle\Domain\Repository\UserRepositoryInterface;
      use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
      
      class UserRepository extends ServiceEntityRepository implements UserRepositoryInterface
      {
          public function findByEmail(string $email): ?User
          {
              return $this->createQueryBuilder('u')
                  ->where('u.email = :email')
                  ->setParameter('email', $email)
                  ->getQuery()
                  ->getOneOrNullResult();
          }
      }
      
  2. Command Bus (CQRS)

    • Dispatch commands via the CommandBus:
      $this->commandBus->dispatch(new CreateUserCommand($data));
      
    • Implement command handlers (e.g., CreateUserCommandHandler) to process commands.
  3. Testing

    • Mock the PluginManager and EventDispatcher in unit tests:
      $pluginManager = $this->createMock(PluginManager::class);
      $pluginManager->method('getPlugin')->willReturn($mockPlugin);
      $this->container->set('companyos_core.plugin_manager', $pluginManager);
      

Gotchas and Tips

Pitfalls

  1. Alpha Version Limitations

    • Missing Migrations: Manually create migrations for new entities using make:migration.
    • Incomplete Controllers: Override or extend core controllers (e.g., src/Controller/ApiController) to avoid NotFoundHttpException.
    • Lack of Tests: Assume edge cases aren’t covered. Write integration tests for critical paths.
  2. Plugin System Quirks

    • Auto-Wiring Issues: Ensure plugins are properly tagged or registered in companyos_core.plugins. Use:
      services:
          App\Plugin\MyPlugin:
              tags: ['companyos_core.plugin']
      
    • Dependency Injection: Plugins may not auto-wire services. Explicitly inject dependencies via constructor:
      public function __construct(private UserServiceInterface $userService)
      {
      }
      
  3. Event-Driven Gotchas

    • Event Order: Events fired in plugins may execute out of expected order. Use priorities in listeners:
      $eventDispatcher->addListener(UserCreatedEvent::class, [$this, 'handleUserCreated'], 10);
      
    • Circular Dependencies: Avoid injecting the EventDispatcher into domain entities. Keep events in the application layer.
  4. Authentication Caveats

    • OAuth2 Configuration: Ensure security.yaml matches your OAuth provider (e.g., password grant type for local auth).
    • Token Storage: Use Symfony’s Security component to store tokens or integrate with lexik/jwt-authentication-bundle.
  5. Performance Tips

    • Lazy-Loading Plugins: Plugins are loaded on-demand. Avoid heavy initialization logic in getName().
    • Caching: Cache plugin instances if frequently accessed:
      $plugin = $this->container->get('companyos_core.plugin_manager')->getPlugin('my_plugin', true);
      

Debugging Tips

  1. Enable Debug Mode Set APP_ENV=dev in .env to see detailed errors and Symfony’s profiler.

  2. Plugin Debugging

    • Check if plugins are loaded via:
      bin/console debug:container | grep companyos_core.plugin_manager
      
    • Verify plugin registration in config/packages/companyos_core.yaml.
  3. Event Listener Debugging

    • List all listeners for an event:
      bin/console debug:event-dispatcher UserCreatedEvent
      
    • Temporarily add a debug listener:
      $eventDispatcher->addListener(UserCreatedEvent::class, function (UserCreatedEvent $event) {
          error_log('Event triggered: ' . $event->getUser()->getId());
      });
      
  4. Doctrine Issues

    • Validate entity mappings:
      bin/console doctrine:schema:validate
      
    • Check for missing repositories by ensuring they implement *RepositoryInterface.

Extension Points

  1. Customizing Core Services

    • Override default services by defining them in config/services.yaml:
      services:
          App\Service\UserService: ~
          CompanyOS\CoreBundle\Domain\Service\UserServiceInterface: '@App\Service\UserService'
      
  2. **Adding New Events

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.
dakiquang/laravel-oauth-refresh-lock
woda/laravel-worktrees
dalefranks/ramasite
faghy/laracashbook
roundly-consulting/google-places-for-laravel
roundly-consulting/kubernetes-api-for-laravel
roundly-consulting/plausible-for-laravel
gvp/gvp-laravel-template
metasyncsite/laravel-metasync-client
roundly-consulting/onboarding-for-laravel
andydefer/laravel-notification
adachsoft/cli-process-tester
jhaskell13/laraflow
sebastienheyd/boilerplate-media-manager
ccast/tagixo-primix
pretendtrue/laravel-builder
sawmainek/laravel-scout-tntsearch-driver
tomshaw/laravel-calendar-table
dibakar/laravel-ownership
adachsoft/changelog-linter