tarik02 / laravel-mixin
Laravel 的混入库
v0.1.0
2020-01-27 15:15 UTC
Requires
- php: >=7.2
- illuminate/console: ^5.5|^6
- illuminate/container: ^5.5|^6
- illuminate/support: ^5.5|^6
- illuminate/view: ^5.5|^6
Requires (Dev)
- laravel/framework: 5.5.x
This package is auto-updated.
Last update: 2024-09-28 01:58:11 UTC
README
将类、一些特质和接口放在一起。例如,在不触及它的情况下向现有模型添加新方法、关系等。这对于将项目拆分为包而不丢失改进能力非常有用。
注意:这只能用于准备使用此包的特殊包。更多信息请见下文。
安装
$ composer require tarik02/laravel-mixin $ mkdir -p storage/framework/mixin $ echo "*\n\!.gitignore" > storage/framework/mixin/.gitignore
命令
此包提供了以下命令
$ php artisan mixin:cache # Cache all mixins and use only cache $ php artisan mixin:cache:clear # Clear mixins cache $ php artisan mixin:generate # Generate all mixins
缓存仅在生产中使用,并在每次代码更改后重新生成。
文档
您可以使用 Sami 生成文档。主分支的文档始终可用,请在此处查看。
注意
您应在应用程序启动阶段仅使用此包的所有方法。在其他阶段使用它们可能会导致未定义的行为。
使用示例
创建您的模型类(注意,该类是 abstract
)
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * App\Models\Article * * @property int $id * @property string $title * @property string $description * @property string $text * @property \Illuminate\Support\Carbon|null $created_at * @property \Illuminate\Support\Carbon|null $updated_at * @property \Illuminate\Support\Carbon|null $deleted_at */ abstract class Article extends Model { // }
创建 App\Providers\MixinServiceProvider
<?php namespace App\Providers; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\ServiceProvider; class MixinServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // } /** * Bootstrap any application services. * * @return void */ public function boot() { $mixin = $this->app->make('mixin'); $mixin ->register(\Models\Article::class, \App\Models\Article::class) ->mixTrait(SoftDeletes::class) ; $mixin ->class(\Models\Article::class) ->mixInterface(MyInterface::class) ; } }
将 MixinServiceProvider
添加到 config/app.php
中 providers
部分的 AppServiceProvider
之前
+ App\Providers\MixinServiceProvider::class, App\Providers\AppServiceProvider::class,
现在您必须使用 \Models\Article
类而不是 \App\Models\Article
(实际上,您可以命名它任何您想要的名称)。
如果您的特质有一个构造函数,您应该在 mixTrait
函数中将 true
作为第二个参数传递。
MixedClass
的构建方法完整列表
mixInterface(string $name)
- 将接口添加到实现部分。mixTrait(string $name, bool $hasConstructor = false)
- 将特质添加到使用部分。useInsteadOf(string $method, string $trait, string $replacedTrait)
- 使用从特质$trait
的名为$method
的方法,而不是从$replacedTrait
的方法。renameMethod(string $trait, string $oldName, string $newName)
- 将特质$trait
的名为$oldName
的方法重命名为$newName
。beforeConstruct(string $code)
- 在父构造函数调用之前添加$code
。afterConstruct(string $code)
- 在父构造函数调用之后添加$code
。code(string $code)
- 将$code
添加到类体中(属性或方法)。
内部机制
实际上,上述代码生成一个扩展指定类、使用指定特质和实现指定接口的类。类位于 storage/framework/mixin
中,并且可以缓存(见缓存部分)。以下是类的样子
<?php namespace Models; use App\Models\Article as Base; class Article extends Base { use \Illuminate\Database\Eloquent\SoftDeletes; }
许可证
此包是开源软件,许可协议为 MIT 许可证。