laravel recipe
1.0.0
Laravel建立的Laravel的发电机框架。
在Laravel 5.5上:
composer require exfriend/laravel-recipe为了生成基本需要两件事的任何实体:模板和实际数据。
食谱将Laravel的刀片用作存根的模板引擎,因此基本用法与您从控制器返回视图的方式非常相似。
让我们写下将生成任何类的第一个食谱。
resources/views/recipe文件夹中创建一个新视图:资源/视图/食谱/class.blade.php
{!! ' < ' . ' ?php ' ! !}
@unless ( empty ( $namespace ) )
namespace {{ $namespace } } ;
@endunless
@unless ( empty ( $imports ) )
@foreach ( $imports as $import )
import {{ $import } } ;
@endforeach
@endunless
class {{ $class } } {{ isset ( $extends ) ? ' extends ' . $extends : ' ' } } {{ ! empty ( $implements ) ? ' implements ' . collect ( $implements ) -> implode ( ' , ' ) : ' ' } }
{
@unless ( empty ( $traits ) )
use {{ collect ( $traits ) -> implode ( ' , ' ) } } ;
@endunless
@isset ( $content )
{!! $content ! !}
@endisset
}
然后,您可以在代码中的任何地方运行:
$recipe = recipe()->usingView( 'recipes.class' )->with( [
'namespace' => 'App',
'class' => 'User',
'extends' => 'Authenticatable',
'imports' => [
'IlluminateFoundationAuthUser as Authenticatable',
'IlluminateNotificationsNotifiable',
'LaravelPassportHasApiTokens',
],
'traits' => [
'HasApiTokens',
'Notifiable',
],
// 'implements' => [ 'SomeInterface', 'OtherInterface' ],
] );
获取编译的代码:
dd ( $ recipe -> build () )保存到文件:
$ recipe -> build ( app_path ( ' User.php ' ) );现在,让我们为此食谱创建一个专门的类,以使其更容易。
app/食谱/classRecipe.php
<?php
namespace App Recipes ;
class ClassRecipe extends Exfriend Recipe Recipe
{
public $ props = [
' class ' => [
' rules ' => ' required ' ,
],
' content ' => [ ' default ' => '' , ],
' imports ' => [ ' default ' => [], ],
];
protected $ view_name = ' recipes.class ' ;
}
在这里,您可以注意到,我们正在硬编码模板名称并定义一个新的$props变量,该变量与Vue在其组件中使用的变量有些相似。
这里发生了两个重要的事情:
首先,我们在此食谱中添加了一些验证,告诉class是必不可少的。您可以像在Laravel应用程序中往常一样设置规则属性 - 这是同一回事。
其次,我们为content和import设置默认值。如果用户不提供任何输入,则将应用这些默认值。
因此,我们所产生的用法现在看起来像这样:
$ recipe = ( App Recipes ClassRecipe::class )-> with ( [
' namespace ' => ' App ' ,
' class ' => ' User ' ,
' extends ' => ' IlluminateFoundationAuthUser ' ,
] )
-> build ( app_path ( ' User.php ' ) );一个重要说明:
由于道具,传递给模板的实际数据将与我们传递的数据略有不同。例如,它将具有content和imports 。有时,您只想使用our编译整个模板的转换数据(例如,嵌套食谱,请参见下文)。要仅获取编译数据,请运行:
$ recipe = ( App Recipes ClassRecipe::class )-> with ( [
...
] )
-> buildData ();由于我们在这里生成一个模型,并且模型是我们要经常生成的东西,因此基于我们已经拥有的通用类食谱创建专用模型配方是有意义的。让我们制作一个简单的模型食谱:
应用/食谱/ModelRecipe.php
即将推出。