Installation
composer require demoniacdeath/cg
Add the service provider to config/app.php under providers:
DemoniacDeath\CG\CGServiceProvider::class,
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!"
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.Workflow:
$enhancements = [
\App\Models\User::class => [
'toJsonArray' => function($user) {
return $user->toArray();
}
]
];
boot() method:
public function boot()
{
$enhancer = app(Enhancer::class);
foreach ($enhancements as $class => $methods) {
$enhancer->enhance($class, $methods);
}
}
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);
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}!";
}
]);
});
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
}
Runtime Overhead
Namespace Collisions
__toString) will overwrite them.if (!method_exists($class, 'newMethod')) {
$enhancer->enhance($class, ['newMethod' => $callback]);
}
PHP 7.2+ Requirement
return_type_declaration and other 7.2+ features. Ensure your server supports it.Reflection Limitations
if (method_exists($obj, 'newMethod')) {
echo 'Method added successfully!';
}
get_declared_methods($obj) to inspect all methods on an object.Enhancer is not auto-bound by default. Manually bind it in a provider:
$this->app->bind(Enhancer::class, function ($app) {
return new Enhancer();
});
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
}
}
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
}
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());
How can I help you explore Laravel packages today?