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

Generic Bundle Laravel Package

cwd/generic-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer in your Laravel project (Symfony-compatible):

    composer require cwd/generic-bundle
    

    Register the bundle in config/app.php under extra.bundles (if using Symfony integration) or wrap it in a Laravel-compatible service provider.

  2. First Use Case: Generic Entities Define a generic entity class (e.g., app/Entities/GenericEntity.php):

    use CWD\GenericBundle\Entity\GenericEntity;
    
    class MyEntity extends GenericEntity {
        protected $fields = [
            'id' => ['type' => 'integer', 'primary' => true],
            'name' => ['type' => 'string'],
            'active' => ['type' => 'boolean', 'default' => false],
        ];
    }
    
  3. Basic CRUD Use the GenericEntityManager to interact with entities:

    $manager = app('cwd_generic.entity_manager');
    $entity = $manager->create('MyEntity', ['name' => 'Test']);
    $manager->save($entity);
    $entities = $manager->findAll('MyEntity');
    
  4. Database Configuration Ensure your config/database.php is properly set up (supports Doctrine-like configurations). For Laravel, use a bridge like doctrine/dbal for compatibility.


Implementation Patterns

Workflow: Entity-Driven Development

  1. Define Schema First Use the bundle’s schema definition to model data before writing controllers:

    class User extends GenericEntity {
        protected $fields = [
            'email' => ['type' => 'string', 'unique' => true],
            'roles' => ['type' => 'array', 'default' => []],
        ];
    }
    
  2. Repository Pattern Extend GenericEntityManager for custom logic:

    class UserRepository extends \CWD\GenericBundle\Manager\GenericEntityManager {
        public function findByRole($role) {
            return $this->findAll('User')->filter(fn($u) => in_array($role, $u->roles));
        }
    }
    
  3. Integration with Laravel Services Bind the manager to Laravel’s IoC container in AppServiceProvider:

    public function register() {
        $this->app->bind('cwd_generic.entity_manager', function($app) {
            return new \CWD\GenericBundle\Manager\GenericEntityManager(
                $app['db'],
                $app['config']['generic_bundle']
            );
        });
    }
    
  4. API Resources Use GenericEntity with Laravel’s API Resources for standardized responses:

    class UserResource extends \Illuminate\Http\Resources\Json\JsonResource {
        public function toArray($request) {
            return parent::toArray($request) + ['meta' => $this->resource->getMetadata()];
        }
    }
    
  5. Event Listeners Leverage Symfony events (e.g., prePersist, postUpdate) via Laravel’s event system:

    // In EventServiceProvider
    protected $listen = [
        'cwd_generic.entity.pre_persist' => [
            \App\Listeners\AuditLogListener::class,
        ],
    ];
    

Gotchas and Tips

Pitfalls

  1. Database Schema Mismatch

    • The bundle dynamically generates tables based on $fields. Ensure your database supports dynamic columns (e.g., avoid strict SQL modes in MySQL).
    • Fix: Use migrations for complex schemas or extend the bundle’s SchemaManager.
  2. Caching Quirks

    • Generic entities cache metadata aggressively. Clear cache after schema changes:
      php artisan cache:clear
      
    • Tip: Use GenericEntity::invalidateCache() for specific entities.
  3. Laravel-Specific Conflicts

    • The bundle assumes Symfony’s EventDispatcher. Bridge it with Laravel’s events:
      $dispatcher = $this->app->make('events');
      $genericDispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();
      $genericDispatcher->addListener(..., function($event) use ($dispatcher) {
          $dispatcher->dispatch(new \App\Events\GenericEvent($event));
      });
      
  4. Performance with Large Datasets

    • Avoid findAll() on tables with millions of rows. Use pagination:
      $manager->findAll('User', ['limit' => 50, 'offset' => 0]);
      

Debugging Tips

  1. Enable Verbose Logging Set debug: true in config/generic_bundle.php to log SQL queries and entity operations.

  2. Schema Validation Use the validateSchema() method to catch misconfigurations early:

    $manager->validateSchema('MyEntity'); // Throws \InvalidArgumentException on errors
    
  3. Hybrid ORM Mode For Laravel Eloquent + GenericBundle hybrid apps, extend GenericEntity and override methods:

    class HybridUser extends GenericEntity {
        public function newQuery() {
            return parent::newQuery()->where('deleted_at', null);
        }
    }
    

Extension Points

  1. Custom Field Types Implement CWD\GenericBundle\Field\FieldTypeInterface for new types (e.g., Json, Enum):

    class JsonFieldType implements FieldTypeInterface {
        public function getSqlType() { return 'json'; }
        public function serialize($value) { return json_encode($value); }
    }
    
  2. Hooks System Override prePersist(), postLoad(), etc., in your entity class for lifecycle logic:

    protected function prePersist() {
        $this->createdAt = now();
    }
    
  3. Query Builder Extensions Add custom methods to GenericEntityManager:

    class ExtendedManager extends GenericEntityManager {
        public function search($entityClass, $query) {
            return $this->createQueryBuilder($entityClass)
                ->where('name LIKE :q')
                ->setParameter('q', "%$query%")
                ->getQuery()
                ->getResult();
        }
    }
    
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.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel