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

Customer Bundle Laravel Package

diego-campos-fivebyfive/customer-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require kolinalabs/customer-bundle
    

    Verify the package appears in composer.json under require.

  2. Enable the Bundle Add to config/bundles.php (Laravel 5.4+) or AppKernel.php (Symfony):

    Kolina\CustomerBundle\KolinaCustomerBundle::class => ['all' => true],
    
  3. Define Your Customer Entity Extend the abstract Customer class in app/Models/Customer.php (Laravel) or src/AppBundle/Entity/Customer.php (Symfony):

    namespace App\Models;
    
    use Kolina\CustomerBundle\Entity\Customer as BaseCustomer;
    
    class Customer extends BaseCustomer
    {
        // Add custom fields/methods (e.g., `protected $phone`)
    }
    
  4. Configure the Bundle In config/kolina_customer.php (Laravel) or config.yml (Symfony):

    kolina_customer:
        entity: App\Models\Customer  # Laravel path
        # entity: AppBundle\Entity\Customer  # Symfony path
    
  5. First Use Case: Create a Customer Inject the manager into a controller/service:

    use Kolina\CustomerBundle\Manager\CustomerManager;
    
    class CustomerController extends Controller
    {
        public function __construct(private CustomerManager $customerManager) {}
    
        public function store(Request $request)
        {
            $customer = $this->customerManager->create();
            $customer->setFirstname($request->firstname);
            $this->customerManager->save($customer);
            return response()->json($customer);
        }
    }
    

Implementation Patterns

Core Workflows

  1. CRUD Operations

    • Create: $manager->create() → Hydrate → $manager->save($customer)
    • Read: $manager->find($id) or $manager->findBy(['email' => '...'])
    • Update: Fetch → Modify → $manager->save($customer)
    • Delete: $manager->remove($customer)
  2. Integration with FOSUserBundle Link customers to FOSUser users via setUser():

    $customer = $manager->create();
    $customer->setUser($fosUserManager->findUserBy(['email' => 'user@example.com']));
    $manager->save($customer);
    
  3. Custom Fields Extend the abstract class and update Doctrine mappings:

    // src/App/Models/Customer.php
    /**
     * @ORM\Column(type="string", length=20)
     */
    protected $phone;
    
  4. Validation Use Symfony’s validator or Laravel’s validation rules:

    $validator = $this->validator->validate($customer);
    if ($validator->count()) { /* Handle errors */ }
    
  5. Events Listen for customer.pre_save/customer.post_save:

    // Laravel (EventServiceProvider)
    protected $listen = [
        'customer.pre_save' => [CustomerEventListener::class, 'onPreSave'],
    ];
    

Best Practices

  • Service Layer: Centralize business logic in a service class (e.g., CustomerService) that uses the manager.
  • Repositories: For complex queries, create a repository class extending CustomerManager.
  • Testing: Mock CustomerManager in unit tests:
    $manager = $this->createMock(CustomerManager::class);
    $manager->method('find')->willReturn($customer);
    

Gotchas and Tips

Pitfalls

  1. Entity Configuration

    • Issue: Forgetting to update config/kolina_customer.php after renaming the Customer class.
    • Fix: Clear cache (php artisan cache:clear) and verify the entity path.
  2. FOSUserBundle Conflicts

    • Issue: If FOSUserBundle is not installed, setUser() will fail.
    • Fix: Install friendsofsymfony/user-bundle or handle the user relation manually.
  3. Doctrine Mappings

    • Issue: Custom fields not persisting due to missing ORM annotations.
    • Fix: Ensure annotations (or YAML/XML mappings) are correctly defined.
  4. Service Not Found

    • Issue: kolina_customer.manager not autowired/injected.
    • Fix: Verify the bundle is registered and the service is defined in services.yaml (Laravel) or services.xml (Symfony).
  5. Event System

    • Issue: Events not firing.
    • Fix: Check event dispatcher configuration and listener tags.

Debugging Tips

  • Log Manager Calls: Wrap manager methods in try-catch blocks to log errors:
    try {
        $manager->save($customer);
    } catch (\Exception $e) {
        \Log::error("Customer save failed: " . $e->getMessage());
    }
    
  • Doctrine Events: Use postFlush to debug entity state:
    $entityManager->getEventManager()->addEventListener(
        \Doctrine\ORM\Events::postFlush,
        function ($event) {
            \Log::debug("Saved entities:", $event->getEntityManager()->getUnitOfWork()->getScheduledEntityInsertions());
        }
    );
    

Extension Points

  1. Custom Manager Extend CustomerManager to add methods:

    namespace App\Services;
    
    use Kolina\CustomerBundle\Manager\CustomerManager as BaseManager;
    
    class CustomerManager extends BaseManager
    {
        public function findByPhone(string $phone): ?Customer
        {
            return $this->createQueryBuilder('c')
                ->where('c.phone = :phone')
                ->setParameter('phone', $phone)
                ->getQuery()
                ->getOneOrNullResult();
        }
    }
    

    Register it as a service alias in config/services.yaml:

    Kolina\CustomerBundle\Manager\CustomerManager: '@App\Services\CustomerManager'
    
  2. Custom Validation Add constraints to the Customer entity:

    use Symfony\Component\Validator\Constraints as Assert;
    
    /**
     * @Assert\Email()
     */
    protected $email;
    
  3. API Resources Use Laravel’s ApiResource or Symfony’s serializers to shape responses:

    // Laravel (ApiResource)
    class CustomerResource extends JsonResource
    {
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'name' => $this->firstname . ' ' . $this->lastname,
                'email' => $this->email,
            ];
        }
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware