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

Contexts Laravel Package

soyuka/contexts

Add lightweight context handling to PHP/Laravel apps with soyuka/contexts. Store and retrieve per-request or runtime context data (like user, locale, tracing IDs) in a clean API to simplify logging, debugging, and cross-cutting concerns without global state.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require soyuka/contexts
    

    Register the extension in your behat.yml:

    extensions:
        Soyuka\Contexts\Extension: ~
    
  2. First Use Case Define a custom context class extending Soyuka\Contexts\Context:

    use Soyuka\Contexts\Context;
    
    class FeatureContext extends Context
    {
        public function iSeeSomething($text)
        {
            // Your logic here
        }
    }
    

    Reference it in your .feature file:

    @javascript
    Feature: Example
      Scenario: Test something
        Given I see something "Hello"
    
  3. Key Files to Review

    • src/Context.php (Base class for custom contexts)
    • src/Extension.php (Configuration and hooks)
    • src/ServiceContainer/ContextExtension.php (Dependency injection)

Implementation Patterns

Workflows

  1. Context Organization

    • Group related steps in dedicated context classes (e.g., AuthContext, PaymentContext).
    • Use namespaces to avoid collisions:
      namespace App\Features\Auth;
      
  2. Step Reusability

    • Extend base contexts for shared functionality:
      class BaseApiContext extends Context
      {
          protected function makeRequest($method, $endpoint, $data = [])
          {
              // Shared HTTP logic
          }
      }
      
  3. Data-Driven Testing

    • Pass arrays/dictionaries to steps for dynamic data:
      When I fill form with:
        | field   | value  |
        | email   | user@example.com |
      
      public function iFillFormWith(array $data)
      {
          foreach ($data as $field => $value) {
              // ...
          }
      }
      
  4. Integration with Laravel

    • Access Laravel services via dependency injection:
      use Illuminate\Contracts\Auth\Guard;
      
      public function __construct(Guard $auth)
      {
          $this->auth = $auth;
      }
      
  5. Hooks for Setup/Teardown

    • Override beforeScenario()/afterScenario() for shared setup:
      protected function beforeScenario()
      {
          $this->auth->loginUsingId(1); // Seed user
      }
      

Integration Tips

  1. Custom Step Matchers

    • Use regex patterns for flexible step definitions:
      /**
       * @Then /^I see "([^"]*)" in "([^"]*)"$/;
      */
      public function iSeeIn($text, $element)
      {
          // ...
      }
      
  2. Parameter Types

    • Define custom parameter types in behat.yml:
      definitions:
        parameters:
          user:
            type: User
            class: App\Models\User
      
  3. Event Dispatching

    • Trigger Laravel events from contexts:
      event(new UserRegistered($user));
      
  4. Mocking Services

    • Use Laravel’s mocking helpers:
      $this->mock(Auth::class)->shouldReceive('check')->andReturn(true);
      
  5. Artisan Commands

    • Execute commands from contexts:
      $this->runArtisan('migrate:fresh');
      

Gotchas and Tips

Pitfalls

  1. Step Name Conflicts

    • Avoid overlapping step definitions (e.g., Given I log in vs. Given I login).
    • Fix: Use unique prefixes (e.g., @auth Given I log in as admin).
  2. State Management

    • Contexts are instantiated per scenario; avoid static state unless intentional.
    • Fix: Use dependency injection for shared services.
  3. Performance

    • Heavy operations in beforeScenario() can slow down tests.
    • Fix: Lazy-load resources or use beforeFeature().
  4. Debugging

    • Steps may fail silently if exceptions aren’t thrown.
    • Fix: Add throw new \Exception("Debug message") for visibility.
  5. Laravel Environment

    • Contexts run in testing environment by default.
    • Fix: Override .env or use app()->setEnvironment('testing').

Debugging Tips

  1. Enable Verbose Output Add to behat.yml:

    default:
      suites:
        default:
          filters:
            tags: "@wip"
      extensions:
        Soyuka\Contexts\Extension:
          verbose: true
    
  2. Logging Inject the logger:

    use Illuminate\Log\Logger;
    
    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
        $this->logger->debug("Context initialized");
    }
    
  3. Step Tracing Use dump() or dd() sparingly (outputs to Behat’s console):

    public function iDoSomething()
    {
        dump($this->someVariable);
    }
    

Extension Points

  1. Custom Parameter Types Extend Soyuka\Contexts\ParameterType for domain-specific types.

  2. Hooks Override:

    • beforeFeature()
    • afterFeature()
    • beforeScenario()
    • afterScenario()
  3. Service Providers Bind custom services to the container:

    $this->getServiceContainer()->set('custom.service', function () {
        return new CustomService();
    });
    
  4. Event Listeners Attach listeners to Behat events:

    $this->getServiceContainer()->getParameter('event_dispatcher')->addListener(
        'beforeScenario',
        [$this, 'customSetup']
    );
    
  5. Configuration Override default settings in behat.yml:

    extensions:
        Soyuka\Contexts\Extension:
            base_context: App\Features\BaseContext
            verbose: false
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope