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

Products Product Laravel Package

baks-dev/products-product

BaksDev Product — модуль продукции для PHP 8.4+: управление продуктами и интеграция с категориями, валютами, деньгами и единицами измерения. Поддерживает установку ассетов, миграции Doctrine и тесты PHPUnit.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies:

    composer require baks-dev/products-category baks-dev/reference-money baks-dev/reference-currency baks-dev/reference-measurement baks-dev/products-product
    

    Verify composer.json for version conflicts with existing packages.

  2. Set Up Configuration:

    php bin/console baks:assets:install
    

    Overrides default config in config/baks.php if needed.

  3. Run Migrations:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    

    Test migrations in a staging DB first with --dry-run.

  4. Register Service Provider: Add to config/app.php:

    Baks\Products\ProductsProductServiceProvider::class,
    
  5. First Use Case: Create a product via Tinker or API:

    use Baks\Products\Entity\Product;
    $product = new Product();
    $product->setName('Test Product');
    $product->setSku('SKU123');
    $product->setPrice(19.99); // Uses reference-money
    $entityManager->persist($product);
    $entityManager->flush();
    

Where to Look First

  • Entities: src/Entity/ for Product, Category, and relationships.
  • Console Commands: src/Command/ for baks:assets:install.
  • Migrations: src/Resources/migrations/ for schema changes.
  • Config: config/baks.php (auto-published by baks:assets:install).

Implementation Patterns

Core Workflows

1. Product CRUD

  • Create:
    $product = (new Product())
        ->setName('Laptop')
        ->setSku('LP-001')
        ->setCategory($categoryEntity)
        ->setPrice(new Money(999.99, 'USD')); // Uses reference-money
    $entityManager->persist($product);
    
  • Retrieve:
    $product = $entityManager->getRepository(Product::class)
        ->findOneBy(['sku' => 'LP-001']);
    
  • Update:
    $product->setPrice(new Money(899.99, 'USD'));
    $entityManager->flush();
    

2. Category Hierarchies

  • Assign Categories:
    $category = $entityManager->getRepository(Category::class)
        ->findOneBy(['name' => 'Electronics']);
    $product->setCategory($category);
    
  • Tree Traversal: Use Doctrine’s TreeRepository (if implemented) or custom traversal:
    function getCategoryPath(Category $category) {
        $path = [$category->getName()];
        while ($parent = $category->getParent()) {
            $path[] = $parent->getName();
            $category = $parent;
        }
        return array_reverse($path);
    }
    

3. Pricing & Measurements

  • Multi-Currency:
    $product->setPrice(new Money(100, 'EUR')); // Auto-converts if needed
    
  • Measurements:
    $product->setWeight(new Measurement(1.5, 'kg')); // Uses reference-measurement
    

4. Bulk Operations

  • CSV Import: Use Laravel’s queue for async processing:

    ProductBulkImporter::dispatch($csvPath)->onQueue('products');
    

    Extend ProductBulkImporter to handle custom logic.

  • API Endpoints:

    Route::post('/products/bulk', [ProductController::class, 'bulkStore']);
    

Integration Tips

Laravel Ecosystem

  • Validation: Extend with Laravel’s FormRequest:

    use Baks\Products\Validator\ProductValidator;
    class StoreProductRequest extends FormRequest {
        public function rules() {
            return array_merge(
                ProductValidator::rules(),
                ['custom_field' => 'required']
            );
        }
    }
    
  • Events: Listen for product events (if not built-in):

    event(new ProductCreated($product));
    

    Extend Product entity to dispatch events.

  • API Resources:

    class ProductResource extends JsonResource {
        public function toArray($request) {
            return [
                'id' => $this->id,
                'name' => $this->name,
                'price' => $this->price->getAmount(),
                'currency' => $this->price->getCurrency()->getCode(),
            ];
        }
    }
    

Frontend

  • Livewire:

    class ProductManager extends Component {
        public $products;
        public function mount() {
            $this->products = Product::all();
        }
        public function render() {
            return view('livewire.product-manager');
        }
    }
    
  • Inertia.js:

    Route::get('/products', [ProductController::class, 'index'])
        ->name('products.index');
    

    Use ProductResource to shape data for Inertia.

Testing

  • Unit Tests:

    public function testProductCreation() {
        $product = new Product();
        $product->setName('Test');
        $this->assertEquals('Test', $product->getName());
    }
    
  • Feature Tests:

    public function testProductApi() {
        $response = $this->post('/api/products', [
            'name' => 'Test Product',
            'sku' => 'TEST123'
        ]);
        $response->assertCreated();
    }
    

Gotchas and Tips

Pitfalls

  1. Doctrine vs. Eloquent:

    • The package uses Doctrine ORM, not Eloquent. Avoid mixing:
      // ❌ Avoid this (unless adapted)
      Product::query()->where('name', 'like', '%test%')->get();
      
    • Use Doctrine’s EntityManager or Repository:
      $repository = $entityManager->getRepository(Product::class);
      $products = $repository->findBy(['name' => 'test']);
      
  2. Migration Conflicts:

    • If using Laravel Migrations, disable Doctrine’s auto-migrations:
      // config/packages/doctrine.php
      doctrine:
          dbal:
              migrations: false
      
    • Run php bin/console doctrine:migrations:migrate separately.
  3. Hardcoded Dependencies:

    • The package requires products-category, reference-money, etc. Install all or risk runtime errors:
      composer require baks-dev/products-category baks-dev/reference-money baks-dev/reference-currency baks-dev/reference-measurement
      
  4. PHP 8.4+ Strictness:

    • Features like named arguments or readonly properties may break older PHP:
      // ❌ May fail in PHP < 8.4
      $product = new Product(name: 'Test');
      
  5. Translation Issues:

    • The README is in Russian. Key terms:
      • Продукция = Products
      • Категории = Categories
      • Цена = Price

Debugging Tips

  1. Query Logging: Enable Doctrine logging in config/packages/doctrine.php:

    doctrine:
        dbal:
            logging: true
            logging_format: '%%timestamp%% %%sql%%'
    
  2. EntityManager Debugging:

    $entityManager->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    
  3. Console Command Errors:

    • Run with -v for verbose output:
      php bin/console baks:assets:install -v
      
  4. Validation Errors:

    • Check ProductValidator in src/Validator/ for custom rules.

Extension Points

  1. Custom Attributes: Extend the Product entity with traits:

    use Baks\Products\Entity\Product;
    use Baks\Products\Trait\HasCustomAttributes;
    
    class ExtendedProduct extends Product {
        use HasCustomAttributes;
    }
    
  2. Repository Overrides: Bind a custom repository in the service provider:

    $this->app->bind(
        \Baks\Products\Repository\ProductRepository::class,
        \App\Repository\CustomProductRepository::class
    );
    
  3. Event Listeners: Add listeners for product lifecycle events:

    // app/Listeners/ProductCreatedListener.php
    public function handle(ProductCreated $event) {
        // Send notification, log, etc.
    }
    
  4. API Extensions: Add custom endpoints:

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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony