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

Philarmony Core Bundle Laravel Package

deozza/philarmony-core-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require deozza/philarmony-core-bundle
    

    Ensure your project uses Symfony 4.2+ and PHP 7.2+.

  2. Configuration Create config/packages/philarmony.yaml with a basic structure:

    deozza_philarmony:
        directory:
            entity: "%kernel.project_dir%/src/Entity"
            repository: "%kernel.project_dir%/src/Repository"
            controller: "%kernel.project_dir%/src/Controller"
            form: "%kernel.project_dir%/src/Form"
            dto: "%kernel.project_dir%/src/DTO"
        database_driver: "doctrine"  # or "eloquent" if using Laravel (not natively supported)
    
  3. First Use Case: Generate a CRUD Module Run the Philarmony command to scaffold a new module (e.g., User):

    php bin/console philarmony:generate:module User
    

    This creates:

    • Entity (src/Entity/User.php)
    • Repository (src/Repository/UserRepository.php)
    • Controller (src/Controller/UserController.php)
    • Form (src/Form/UserType.php)
    • DTO (src/DTO/UserDTO.php)

    Test the API at /api/users (default routes are auto-generated).


Implementation Patterns

Core Workflows

  1. Modular API Development

    • Use philarmony:generate:module for rapid scaffolding.
    • Extend generated classes (e.g., override UserController methods like index() or store()).
    • Example:
      // src/Controller/UserController.php
      public function store(Request $request, UserDTO $dto): Response
      {
          $dto->setCustomField('metadata', ['created_by' => $this->getUser()->getId()]);
          return parent::store($request, $dto);
      }
      
  2. DTO-Driven Validation

    • Philarmony uses Data Transfer Objects (DTOs) for request/response validation.
    • Customize validation in DTOs:
      // src/DTO/UserDTO.php
      #[Assert\NotBlank]
      private ?string $email;
      
      #[Assert\Length(min: 8)]
      private ?string $password;
      
  3. Repository Patterns

    • Extend PhilarmonyRepository for custom queries:
      // src/Repository/UserRepository.php
      public function findActiveUsers(): array
      {
          return $this->createQueryBuilder('u')
              ->where('u.is_active = :active')
              ->setParameter('active', true)
              ->getQuery()
              ->getResult();
      }
      
  4. Authorization

    • Use Philarmony’s built-in Voter system:
      # config/packages/security.yaml
      security:
          access_control:
              - { path: ^/api/users, roles: ROLE_USER }
      
    • Create custom voters:
      // src/Security/Voter/UserVoter.php
      public function supportsAttribute($attribute): bool
      {
          return $attribute === 'EDIT_USER';
      }
      
      public function vote(AuthenticatedToken $token, $object, array $attributes): bool
      {
          return $token->getUser()->getId() === $object->getId();
      }
      
  5. API Versioning

    • Enable versioning via philarmony.yaml:
      deozza_philarmony:
          versioning: true
      
    • Access routes via /api/v1/users or /api/v2/users.

Integration Tips

  1. Doctrine vs. Eloquent

    • Philarmony defaults to Doctrine ORM. For Eloquent (Laravel), override the DatabaseDriver service or use a wrapper.
  2. Custom Serialization

    • Extend PhilarmonySerializer to modify JSON output:
      // src/Serializer/CustomSerializer.php
      public function serialize($data, $format, array $context = [])
      {
          $context['groups'] = ['api', 'custom_group'];
          return parent::serialize($data, $format, $context);
      }
      
  3. Event Listeners

    • Hook into lifecycle events (e.g., prePersist):
      // src/EventListener/UserListener.php
      public function onPrePersist(User $user): void
      {
          $user->setCreatedAt(new \DateTime());
      }
      
      Register in services.yaml:
      services:
          App\EventListener\UserListener:
              tags:
                  - { name: 'kernel.event_listener', event: 'philarmony.pre_persist', method: 'onPrePersist' }
      
  4. Testing

    • Use Philarmony’s test utilities:
      // tests/Controller/UserControllerTest.php
      public function testCreateUser()
      {
          $client = static::createClient();
          $client->request('POST', '/api/users', [
              'json' => ['name' => 'Test', 'email' => 'test@example.com']
          ]);
          $this->assertResponseStatusCodeSame(201);
      }
      

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts

    • Ensure directory paths in philarmony.yaml match your project’s autoloading (e.g., src/ vs. app/).
    • Fix: Verify composer.json autoload paths and clear cache:
      composer dump-autoload
      php bin/console cache:clear
      
  2. DTO Validation Overrides

    • Custom DTO validation may conflict with Philarmony’s default constraints.
    • Fix: Use #[Assert\Callback] for complex rules:
      #[Assert\Callback]
      public function validate(ExecutionContextInterface $context, $payload): void
      {
          if ($payload['email'] === 'admin@example.com') {
              $context->buildViolation('Admin emails are restricted.')
                  ->atPath('email')
                  ->addViolation();
          }
      }
      
  3. Repository Caching Issues

    • Doctrine queries may not respect Philarmony’s caching layer if not configured.
    • Fix: Explicitly enable caching in repositories:
      public function __construct(EntityManagerInterface $em)
      {
          parent::__construct($em);
          $this->setCacheable(true);
      }
      
  4. Symfony 5+ Deprecations

    • Philarmony is optimized for Symfony 4.2. Some Symfony 5+ features (e.g., Attribute router) may require manual adjustments.
    • Fix: Check the Symfony Upgrade Guide and override Philarmony’s routing logic.
  5. Missing Dependencies

    • The bundle assumes DoctrineBundle and SerializerComponent are installed.
    • Fix: Install missing packages:
      composer require doctrine/doctrine-bundle symfony/serializer-pack
      

Debugging Tips

  1. Enable Verbose Logging Add to config/packages/dev/philarmony.yaml:

    deozza_philarmony:
        debug: true
    

    Logs appear in var/log/dev.log.

  2. Command-Line Debugging Use philarmony:debug to inspect generated modules:

    php bin/console philarmony:debug
    
  3. Common Errors

    Error Solution
    Class not found Verify directory paths in philarmony.yaml and run composer dump-autoload.
    Validation failed Check DTO constraints and request payloads.
    Route not found Ensure versioning is configured and routes are flushed (php bin/console router:debug).
    Database connection failed Validate DATABASE_URL in .env and Doctrine configuration.

Extension Points

  1. Custom Generators Extend the ModuleGenerator class to add fields or logic during scaffolding:

    // src/Generator/CustomModuleGenerator.php
    public function generateModule(string $moduleName): void
    {
        parent::generateModule($moduleName);
        $this->addCustomField($moduleName, 'is_active', 'boolean', false);
    }
    
  2. API Middleware Add middleware to Philarmony’s pipeline:

    # config/packages/philarmony.yaml
    deozza_philarmony:
        middleware:
            - App\Middleware\LogApiRequests
    
  3. Database Drivers Implement a custom DatabaseDriverInterface for non-Doctrine/Eloquent databases (e.g., MongoDB):

    class MongoDriver implements DatabaseDriverInterface
    {
        public function find($entity, $id): ?object
        {
            // Custom MongoDB logic
        }
    }
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
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