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

Definitions Laravel Package

yiisoft/definitions

Lightweight definitions library for Yii and PHP DI containers. Provides a consistent way to describe services, factories, references, and parameters for building dependency graphs, resolving callables, and configuring containers with minimal overhead.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require yiisoft/definitions
    

    No additional configuration is required for basic usage.

  2. First Use Case: Defining a Service Define a service (e.g., a logger) using the Definition class:

    use Yiisoft\Definitions\Definition;
    use Yiisoft\Definitions\DefinitionInterface;
    
    $loggerDefinition = Definition::create()
        ->className(\Psr\Log\LoggerInterface::class)
        ->constructor([
            Definition::create()->className(\Psr\Log\Handler\StreamHandler::class)
                ->constructor(['/path/to/logs/app.log'])
                ->method('setFormatter', Definition::create()->className(\Psr\Log\Formatter\LineFormatter::class))
        ]);
    
  3. Where to Look First

    • Core Classes: Focus on Definition, DefinitionInterface, and DefinitionContainer.
    • Examples: Check the Yii Framework repositories for real-world usage (e.g., how they define services in their applications).
    • API Docs: The package is part of the Yii Software Foundation ecosystem, so refer to their documentation for method signatures and behavior.

Implementation Patterns

Common Workflows

  1. Service Definition Use Definition to configure services with dependencies, constructors, and methods:

    $repositoryDefinition = Definition::create()
        ->className(\App\Repositories\UserRepository::class)
        ->constructor([
            Definition::create()->className(\App\Services\Database::class)
        ]);
    
  2. Dynamic Configuration Leverage Definition to inject configuration dynamically:

    $configurableService = Definition::create()
        ->className(\App\Services\ConfigurableService::class)
        ->method('setConfig', Definition::create()->value(['key' => 'value']));
    
  3. Integration with Laravel's Service Container Use the DefinitionContainer to resolve definitions in Laravel's IoC container:

    $container = new \Yiisoft\Definitions\DefinitionContainer();
    $container->setDefinitions([
        'logger' => $loggerDefinition,
    ]);
    $logger = $container->get('logger'); // Resolves the logger service
    
  4. Grouping Definitions Organize definitions hierarchically for complex applications:

    $definitions = [
        'database' => Definition::create()->className(\App\Services\Database::class),
        'userRepository' => Definition::create()
            ->className(\App\Repositories\UserRepository::class)
            ->constructor([Definition::create()->reference('database')]),
    ];
    $container->setDefinitions($definitions);
    
  5. Lazy Loading Use Definition::lazy() to defer instantiation until first use:

    $lazyService = Definition::create()
        ->lazy()
        ->className(\App\Services\HeavyService::class);
    

Integration Tips

  • Laravel Service Providers Register definitions in a Laravel service provider:

    public function register()
    {
        $container = new \Yiisoft\Definitions\DefinitionContainer();
        $this->app->singleton('definitions', fn() => $container);
    }
    
  • Configuration Files Store definitions in config/definitions.php and load them in a service provider:

    $definitions = require config_path('definitions.php');
    $container->setDefinitions($definitions);
    
  • Testing Mock definitions in tests for isolated service resolution:

    $mockDefinition = Definition::create()->value(new \App\Mocks\MockService());
    $container->setDefinitions(['mockService' => $mockDefinition]);
    

Gotchas and Tips

Pitfalls

  1. Circular Dependencies Avoid circular references between definitions. The container will throw an exception if detected:

    // ❌ Avoid this:
    $definitions = [
        'a' => Definition::create()->constructor([Definition::create()->reference('b')]),
        'b' => Definition::create()->constructor([Definition::create()->reference('a')]),
    ];
    
  2. Immutable Definitions Definitions are immutable after creation. Use method chaining to build them:

    // ❌ Won't work:
    $definition->constructor([...]); // Throws error if called after creation.
    
    // ✅ Correct:
    Definition::create()->constructor([...]);
    
  3. Non-Existent References Always ensure referenced definitions exist when resolving:

    // ❌ Throws exception if 'nonexistent' isn't defined:
    Definition::create()->constructor([Definition::create()->reference('nonexistent')]);
    
  4. Type Safety The package doesn’t enforce type hints for constructor arguments. Validate manually or use PHP 8+ return types:

    // Ensure the constructor matches the class's type hints.
    

Debugging Tips

  1. Inspect Definitions Use DefinitionContainer::getDefinition() to debug unresolved definitions:

    $definition = $container->getDefinition('serviceName');
    dump($definition->toArray()); // Inspect raw definition structure.
    
  2. Enable Strict Mode Set DefinitionContainer::setStrictMode(true) to catch issues early (e.g., missing definitions).

  3. Logging Resolution Override DefinitionContainer to log resolution steps:

    $container = new class extends \Yiisoft\Definitions\DefinitionContainer {
        protected function resolveDefinition(DefinitionInterface $definition): mixed {
            \Log::debug('Resolving: ' . $definition->className);
            return parent::resolveDefinition($definition);
        }
    };
    

Extension Points

  1. Custom Resolvers Extend DefinitionContainer to add custom resolution logic:

    class CustomContainer extends \Yiisoft\Definitions\DefinitionContainer {
        protected function resolveDefinition(DefinitionInterface $definition): mixed {
            if ($definition->className === \App\Services\CustomService::class) {
                return new \App\Services\CustomService($this->get('config'));
            }
            return parent::resolveDefinition($definition);
        }
    }
    
  2. Definition Factories Create reusable factories for common definitions:

    class LoggerFactory {
        public static function create(string $path): DefinitionInterface {
            return Definition::create()
                ->className(\Psr\Log\LoggerInterface::class)
                ->constructor([
                    Definition::create()
                        ->className(\Psr\Log\Handler\StreamHandler::class)
                        ->constructor([$path])
                ]);
        }
    }
    
  3. Integration with Laravel Bindings Combine with Laravel’s bind() for hybrid resolution:

    $this->app->bind(\App\Contracts\UserRepository::class, function ($app) {
        $container = $app->make('definitions');
        return $container->get('userRepository');
    });
    
  4. Environment-Aware Definitions Dynamically adjust definitions based on environment (e.g., staging vs. production):

    $definition = Definition::create()
        ->className(\App\Services\Cache::class)
        ->constructor([
            Definition::create()->value(config('cache.driver') === 'redis' ? 'redis' : 'file')
        ]);
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4