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

Cg Laravel Package

demoniacdeath/cg

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require demoniacdeath/cg
    

    Add the service provider to config/app.php under providers:

    DemoniacDeath\CG\CGServiceProvider::class,
    
  2. First Use Case: Class Enhancement Use the Enhancer to dynamically add methods to existing classes:

    use DemoniacDeath\CG\Enhancer;
    
    $enhancer = new Enhancer();
    $enhancer->enhance(\stdClass::class, [
        'newMethod' => function($obj) {
            return 'Enhanced!';
        }
    ]);
    
    $obj = new \stdClass();
    echo $obj->newMethod(); // Output: "Enhanced!"
    
  3. Key Files to Review

    • src/Enhancer.php: Core logic for class enhancement.
    • src/Generator.php: Code generation utilities.
    • src/Traits/: Predefined behaviors for common use cases.

Implementation Patterns

Dynamic Method Injection

Workflow:

  1. Define Enhancements in a dedicated service or config file:
    $enhancements = [
        \App\Models\User::class => [
            'toJsonArray' => function($user) {
                return $user->toArray();
            }
        ]
    ];
    
  2. Apply Globally in a service provider’s boot() method:
    public function boot()
    {
        $enhancer = app(Enhancer::class);
        foreach ($enhancements as $class => $methods) {
            $enhancer->enhance($class, $methods);
        }
    }
    

Code Generation for Models

Use Case: Auto-Generate Accessors

use DemoniacDeath\CG\Generator;

$generator = new Generator();
$modelCode = $generator->generateModel(
    'User',
    ['name', 'email'],
    ['getFullName' => 'return ucfirst($this->name);']
);
file_put_contents(app_path('Models/User.php'), $modelCode);

Integration with Laravel Events

Pattern: Enhance Models on Demand

use Illuminate\Support\Facades\Event;

Event::listen('eloquent.created: App\Models\User', function ($user) {
    $enhancer = app(Enhancer::class);
    $enhancer->enhance($user, [
        'getGreeting' => function() {
            return "Hello, {$this->name}!";
        }
    ]);
});

Traits for Reusability

Example: Add a Serializable trait to multiple models

use DemoniacDeath\CG\Traits\Serializable;

class User extends Model
{
    use Serializable;

    // Automatically gains `toJson()` and `fromJson()` methods
}

Gotchas and Tips

Pitfalls

  1. Runtime Overhead

    • Dynamically added methods are resolved at runtime, which may impact performance in tight loops.
    • Mitigation: Cache enhanced classes or use traits for static behaviors.
  2. Namespace Collisions

    • Enhancing classes with methods that conflict with existing ones (e.g., __toString) will overwrite them.
    • Mitigation: Prefix method names or validate before enhancement:
      if (!method_exists($class, 'newMethod')) {
          $enhancer->enhance($class, ['newMethod' => $callback]);
      }
      
  3. PHP 7.2+ Requirement

    • Uses return_type_declaration and other 7.2+ features. Ensure your server supports it.
  4. Reflection Limitations

    • Enhancing final classes or methods may throw errors. Test thoroughly.

Debugging

  • Verify Enhancements:
    if (method_exists($obj, 'newMethod')) {
        echo 'Method added successfully!';
    }
    
  • Check for Overwrites: Use get_declared_methods($obj) to inspect all methods on an object.

Configuration Quirks

  • Service Provider Binding: The Enhancer is not auto-bound by default. Manually bind it in a provider:
    $this->app->bind(Enhancer::class, function ($app) {
        return new Enhancer();
    });
    

Extension Points

  1. Custom Generators Extend DemoniacDeath\CG\Generator to add domain-specific templates:

    class ApiResourceGenerator extends Generator
    {
        public function generateResource(string $name, array $fields): string
        {
            // Custom logic
        }
    }
    
  2. Hooks for Enhancement Override Enhancer::shouldEnhance() to add conditional logic:

    protected function shouldEnhance(string $class, array $methods): bool
    {
        return strpos($class, 'App\\') === 0; // Only enhance app classes
    }
    
  3. Integration with Laravel Mix Use the Generator to auto-generate API clients or DTOs during build:

    // In a custom webpack.mix.js plugin
    mix.extend('generateModels', new GenerateModelsPlugin());
    
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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle