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

Bdf Prime Bundle Laravel Package

b2pweb/bdf-prime-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require b2pweb/bdf-prime-bundle
    

    Add to config/bundles.php:

    Bdf\PrimeBundle\PrimeBundle::class => ['all' => true],
    Bdf\PrimeBundle\TestingPrimeBundle::class => ['test' => true],
    
  2. Configure .env

    DATABASE_URL=mysql://user:pass@host/dbname?serverVersion=5.7
    
  3. Basic Config (config/packages/prime.yaml)

    prime:
        activerecord: true
        connections:
            default: '%env(resolve:DATABASE_URL)%'
    
  4. First Use Case: Define a Model

    // src/Model/User.php
    namespace App\Model;
    
    use Bdf\Prime\ActiveRecord\Model;
    
    class User extends Model
    {
        public static string $table = 'users';
        public ?int $id;
        public string $name;
        public string $email;
    }
    

    Usage:

    $user = User::find(1);
    $user->save();
    

Implementation Patterns

Active Record Workflow

  1. CRUD Operations

    // Create
    $user = new User();
    $user->name = 'John Doe';
    $user->email = 'john@example.com';
    $user->save();
    
    // Read
    $user = User::find(1);
    $users = User::all();
    
    // Update
    $user->name = 'Updated Name';
    $user->save();
    
    // Delete
    $user->delete();
    
  2. Query Builder

    $activeUsers = User::where('active', true)->orderBy('name')->get();
    $count = User::count();
    
  3. Relationships

    // One-to-Many
    class Post extends Model
    {
        public static string $table = 'posts';
        public ?int $user_id;
        public string $title;
        public User $user; // BelongsTo
    }
    
    class User extends Model
    {
        public static string $table = 'users';
        public ?int $id;
        public string $name;
        public array $posts = []; // HasMany
    }
    
  4. Transactions

    User::transaction(function () {
        $user = new User();
        $user->name = 'Alice';
        $user->save();
    
        $post = new Post();
        $post->title = 'Hello';
        $post->user_id = $user->id;
        $post->save();
    });
    

Integration with Doctrine

  1. Hybrid Approach Use activerecord: false in prime.yaml and manually map models to Doctrine entities:

    prime:
        activerecord: false
        hydrators: '%kernel.cache_dir%/prime/hydrators/loader.php'
    
  2. Custom Hydrators Override hydrators for complex mappings:

    // src/Prime/Hydrator/UserHydrator.php
    namespace App\Prime\Hydrator;
    
    use Bdf\Prime\Hydrator\HydratorInterface;
    use App\Model\User;
    
    class UserHydrator implements HydratorInterface
    {
        public function hydrate(array $data): User
        {
            $user = new User();
            $user->id = $data['id'] ?? null;
            $user->name = $data['name'] ?? '';
            $user->email = $data['email'] ?? '';
            return $user;
        }
    }
    
  3. Event Listeners

    // src/EventListener/UserListener.php
    namespace App\EventListener;
    
    use Bdf\Prime\Event\UserEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class UserListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                UserEvent::PRE_SAVE => 'onPreSave',
            ];
        }
    
        public function onPreSave(UserEvent $event): void
        {
            $user = $event->getUser();
            $user->email = strtolower($user->email);
        }
    }
    

Testing Patterns

  1. Test Configuration

    # config/packages/test/prime.yaml
    prime:
        logging: true
        cache:
            query: { pool: null, service: null }
            metadata: { pool: null, service: null }
    
  2. Test Fixtures

    // tests/PrimeFixtures/UserFixtures.php
    namespace App\Tests\PrimeFixtures;
    
    use Bdf\Prime\Fixture\FixtureInterface;
    use App\Model\User;
    
    class UserFixtures implements FixtureInterface
    {
        public function load(): void
        {
            $user = new User();
            $user->name = 'Test User';
            $user->email = 'test@example.com';
            $user->save();
        }
    }
    
  3. Unit Tests

    // tests/Unit/UserTest.php
    use App\Model\User;
    use PHPUnit\Framework\TestCase;
    
    class UserTest extends TestCase
    {
        public function testSaveUser(): void
        {
            $user = new User();
            $user->name = 'Test';
            $user->email = 'test@example.com';
            $user->save();
    
            $this->assertNotNull($user->id);
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. Connection Issues

    • Ensure DATABASE_URL in .env matches your database schema (e.g., mysql://user:pass@host/dbname).
    • For SQLite in tests, use sqlite::memory: and ensure the prime.yaml test config disables caching.
  2. Caching Quirks

    • Production: Enable caching for performance:
      prime:
          cache:
              query:
                  service: 'Bdf\Prime\Cache\ArrayCache'
              metadata:
                  pool: 'cache.app'
      
    • Development: Disable caching for debugging:
      prime:
          cache:
              query: { pool: null, service: null }
              metadata: { pool: null, service: null }
      
  3. Active Record vs. Data Mapper

    • If activerecord: true, models are tightly coupled to the database schema. For flexibility, set activerecord: false and use custom hydrators.
  4. Migration Path Conflicts

    • Ensure the migration.path in prime.yaml points to a valid directory:
      prime:
          migration:
              path: '%kernel.project_dir%/src/Migration'
      
    • Run migrations manually if needed:
      php bin/console prime:migrate
      

Debugging Tips

  1. Enable Logging

    prime:
        logging: true
    

    Check logs in var/log/dev.log for SQL queries and errors.

  2. Query Inspection Use the PrimeBundle profiler to inspect executed queries:

    // In a controller or command
    $query = User::where('active', true);
    dump($query->getQuery()->getSql());
    
  3. Hydrator Debugging Override hydrators to log data:

    public function hydrate(array $data): User
    {
        error_log(print_r($data, true)); // Debug raw data
        return parent::hydrate($data);
    }
    

Extension Points

  1. Custom Query Builders Extend the query builder for domain-specific methods:

    // src/Prime/Query/UserQueryBuilder.php
    namespace App\Prime\Query;
    
    use Bdf\Prime\Query\QueryBuilder;
    
    class UserQueryBuilder extends QueryBuilder
    {
        public function active(): self
        {
            return $this->where('active', true);
        }
    }
    
  2. Event Dispatching Subscribe to events for pre/post hooks:

    // src/EventSubscriber/UserSubscriber.php
    use Bdf\Prime\Event\UserEvent;
    
    class UserSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                UserEvent::PRE_SAVE => 'onPreSave',
                UserEvent::POST_SAVE => 'onPostSave',
            ];
        }
    }
    
  3. Custom Fixtures Load test data dynamically:

    // tests/PrimeFixtures/LoadFixtures.php
    namespace App\Tests\PrimeFixtures;
    
    use Bdf\Prime\Fixture\FixtureLoader;
    
    class LoadFixtures
    {
        public function __invoke(): void
        {
            (new FixtureLoader())->load([new UserFixtures()]);
        }
    }
    

Performance Optimization

  1. Batch Operations Use insert() for bulk inserts:
    User::insert([
        ['name' => 'User
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky