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

Budget Laravel Package

chill-project/budget

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require chill-project/budget
    

    Add the bundle to your config/bundles.php:

    return [
        // ...
        Chill\Budget\BudgetBundle::class => ['all' => true],
    ];
    
  2. Database Migration Run the migrations to create required tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Use Case Create a budget for a user (e.g., in a controller):

    use Chill\Budget\Budget;
    use Chill\Budget\BudgetRepository;
    
    $budgetRepo = $this->getDoctrine()->getRepository(Budget::class);
    $budget = $budgetRepo->createBudgetForUser($user, '2024', 'Monthly');
    $budgetRepo->save($budget);
    
  4. Key Classes to Explore

    • Budget (entity): Represents a budget (e.g., monthly, yearly).
    • BudgetItem (entity): Tracks individual budget entries (income/expense).
    • BudgetRepository: CRUD operations for budgets.
    • BudgetService: Business logic (e.g., validation, calculations).

Implementation Patterns

Common Workflows

1. Creating and Managing Budgets

  • User-Specific Budgets:
    $budget = $budgetService->createBudget($user, '2024', 'Monthly', 2000); // $2k limit
    
  • Bulk Creation:
    $budgetService->createBudgetsForUsers($users, '2024', 'Yearly');
    

2. Adding Budget Items

  • Income/Expense Tracking:
    $budgetItem = $budgetService->addItem($budget, 'Rent', -500, 'Expense');
    $budgetItem = $budgetService->addItem($budget, 'Salary', 3000, 'Income');
    

3. Validation and Rules

  • Custom Rules:
    $budgetService->addRule($budget, 'max_expenses', 3); // Limit to 3 expenses
    $budgetService->addRule($budget, 'min_income', 2500); // Require $2.5k income
    
  • Check Compliance:
    if (!$budgetService->isValid($budget)) {
        $errors = $budgetService->getValidationErrors($budget);
    }
    

4. Reporting

  • Summary for a Budget:
    $summary = $budgetService->getSummary($budget);
    // Returns: ['total_income', 'total_expense', 'balance', 'items']
    
  • Periodic Reports:
    $monthlyReport = $budgetService->generateMonthlyReport($user, '2024-01');
    

5. Integration with Chill

  • Link to User Profiles: Extend the User entity to include a budget relationship:
    // src/Entity/User.php
    /**
     * @ORM\OneToOne(targetEntity="Chill\Budget\Budget", mappedBy="user")
     */
    private $budget;
    
  • Event Listeners: Trigger actions on budget changes (e.g., notifications):
    // config/services.yaml
    Chill\Budget\EventListener\BudgetListener::class:
        tags:
            - { name: doctrine.event_listener, event: postPersist }
            - { name: doctrine.event_listener, event: postUpdate }
    

Integration Tips

API Endpoints

Use Symfony’s ApiPlatform or FOSRestBundle to expose budgets:

# config/api_platform/resources.yaml
resources:
    Chill\Budget\Entity\Budget:
        collectionOperations:
            get: ~
            post: ~
        itemOperations:
            get: ~
            put: ~
            delete: ~

Frontend Integration

  • Vue/React Hooks: Subscribe to budget changes via WebSocket (e.g., Mercure):

    // Subscribe to budget updates
    const eventSource = new EventSource('/.well-known/mercure?topic=/updates/budget');
    eventSource.onmessage = (e) => {
        const data = JSON.parse(e.data);
        this.budget = data.budget;
    };
    
  • Templates: Use Twig to display budgets:

    {% for item in budget.items %}
        <div class="budget-item">
            {{ item.label }}: {{ item.amount | currency }}
            <span class="type {{ item.type|lower }}">
                {{ item.type }}
            </span>
        </div>
    {% endfor %}
    

Gotchas and Tips

Pitfalls

  1. Circular Dependencies

    • Avoid circular references between Budget and User entities. Use lazy loading or explicit fetch in repositories:
      $budget = $budgetRepo->findOneBy(['user' => $user], ['items' => 'LEFT']);
      
  2. Validation Overhead

    • Custom rules may slow down bulk operations. Cache validation results for frequent checks:
      $budgetService->cacheValidation($budget, 3600); // Cache for 1 hour
      
  3. Concurrency Issues

    • Budget updates (e.g., adding items) may conflict. Use optimistic locking:
      // In Budget.php
      /**
       * @ORM\Versioned
       */
      private $version;
      
  4. Date Handling

    • Ensure budget periods (e.g., "Monthly") align with your application’s date logic. Override the getPeriod() method in Budget if needed:
      public function getPeriod(): string
      {
          return Carbon::parse($this->startDate)->format('Y-m');
      }
      

Debugging

  1. Query Logging Enable Doctrine debugging to inspect queries:

    # config/packages/dev/doctrine.yaml
    doctrine:
        dbal:
            logging: true
            profiler: true
    
  2. Common Errors

    • BudgetPeriodNotFoundException: Ensure the period (e.g., "2024") matches the Budget entity’s period field.
    • ValidationFailedException: Check rules in BudgetService and validate manually:
      $budgetService->validate($budget);
      
  3. Event Debugging Dump events in a listener:

    use Symfony\Component\HttpKernel\Event\KernelEvent;
    
    public function onKernelRequest(KernelEvent $event)
    {
        if ($event->isMainRequest()) {
            dump($event->getRequest()->attributes->all());
        }
    }
    

Tips

  1. Extending Functionality

    • Custom Budget Types: Create a BudgetType entity and extend Budget:
      // src/Entity/CustomBudget.php
      class CustomBudget extends Budget
      {
          private $customField;
      
          // Add getters/setters and override methods as needed.
      }
      
    • Plugins: Use Symfony’s CompilerPass to dynamically register services:
      public function process(ContainerBuilder $container)
      {
          $container->register('custom_budget_plugin', CustomBudgetPlugin::class)
              ->addTag('chill.budget.plugin');
      }
      
  2. Performance

    • Batch Processing: Use Doctrine’s BATCH_SIZE for bulk inserts:
      $em->getConnection()->getConfiguration()->setSQLLogger(null); // Disable logging
      $em->flush();
      $em->getConnection()->getConfiguration()->setSQLLogger($logger);
      
    • Indexing: Add indexes to frequently queried fields (e.g., user_id, period):
      /**
       * @ORM\Index(name="idx_user_period", columns={"user_id", "period"})
       */
      
  3. Testing

    • Fixtures: Use Nelmio/AliceBundle to seed test data:
      # tests/fixtures/budget.yml
      Chill\Budget\Entity\Budget:
          budget1:
              user: user1
              period: '2024'
              type: 'Monthly'
              limit: 2000
      
    • Mocking: Mock the BudgetService in unit tests:
      $budgetService = $this->createMock(BudgetService::class);
      $budgetService->method('isValid')->willReturn(true);
      
  4. Configuration

    • Customize Defaults: Override bundle settings in config/packages/chill_budget.yaml:
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.
alphabalex/messaging-made-easy
rawphp/warp
shootkiran/merobug
narakode/fineauth
numencode/wn-syncops-plugin
ibnnajjaar/mib-global-pay
ably/pubsub-server
mstfkhazaal/defender
mfonte/base62x
karnoweb/metapilot
tobya/bcsapiwrapper
swalker2/cpanel
vish4395/laravel-translation-manager
morningtrain/economic
teksite/systeminfo-laravel
atomcms/voting
run6/weather
siokas/laravelembeddirectives
adamlien/pkuuids
gilsonsouza/lara-doc-generator