laraditz/action

Laravel和Lumen的单个操作类,以保持您的应用程序DRY

安装次数: 1,377

依赖项: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 0

公开问题: 0

类型:laravel-package

1.0.2 2020-08-23 14:11 UTC

This package is auto-updated.

Last update: 2024-09-23 22:59:40 UTC


README

Latest Stable Version Total Downloads License StyleCI

Laravel和Lumen的单个操作类,以保持您的应用程序DRY。

安装

通过Composer

$ composer require laraditz/action

配置

由于Laravel和Lumen的配置略有不同,因此以下是每个框架的安装说明。

Laravel

编辑config/app.php文件,并添加以下行以注册服务提供者

'providers' => [
    ...
    Laraditz\Action\ActionServiceProvider::class,
    ...
],

提示:如果您使用的是Laravel版本5.5或更高,您可以跳过此设置部分,转而使用自动发现功能。

Lumen

编辑bootstrap/app.php文件,并添加以下行以注册服务提供者

...
$app->register(Laraditz\Action\ActionServiceProvider::class);
...

用法

您可以使用php artisan make:action <name>来创建您的操作。例如,php artisan make:action CreateNewPost。默认情况下,您可以在App/Actions文件夹中找到它。

生成的示例操作文件,其中添加了一些逻辑如下

namespace App\Actions;

use Laraditz\Action\Action;

class CreateNewPost extends Action
{
    // Optional
    public function rules()
    {
        return [
            'title' => 'required',
            'body' => 'required|min:10',
        ];
    }

    public function handle()
    {
        // Your logic goes here
        \App\Post::create($this->validated());

        // use $this->validated() to get all validated attributes based on rules.
        // You also can use $this->all() to retreive all attributes passed if there is no rules.
    }
}

您还可以在handle方法上使用依赖注入(DI)。

...
public function handle(Request $request)
{
    // Your logic goes here        
}
...

如果您不使用它,可以完全删除rules方法,或者保留原样。

现在您已经创建了操作,您可以以下几种方式调用它

使用普通对象

$createNewPost = new CreateNewPost([
    'title' => 'My first post', 
    'body' => 'This is a post content'
]);

$createNewPost->dispatch();

使用静态方法

CreateNewPost::dispatch([
    'title' => 'My first post', 
    'body' => 'This is a post content'
]);

使用可调用的

// routes/web.php
Route::post('posts', '\App\Actions\CreateNewPost');

致谢

许可证

MIT。请参阅许可证文件以获取更多信息。