laraditz/action

Single action class for Laravel and Lumen to keep your application DRY

Installs: 1 378

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 2

Forks: 0

Open Issues: 0

Type:laravel-package

1.0.2 2020-08-23 14:11 UTC

This package is auto-updated.

Last update: 2024-11-23 23:27:03 UTC


README

Latest Stable Version Total Downloads License StyleCI

Single action class for Laravel and Lumen to keep your application DRY.

Installation

Via Composer

$ composer require laraditz/action

Configuration

The Laravel and Lumen configurations vary slightly, so here are the instructions for each of the frameworks.

Laravel

Edit the config/app.php file and add the following line to register the service provider:

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

Tip: If you're on Laravel version 5.5 or higher, you can skip this part of the setup in favour of the Auto-Discovery feature.

Lumen

Edit the bootstrap/app.php file and add the following line to register the service provider:

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

Usage

You can use php artisan make:action <name> to create your action. For example, php artisan make:action CreateNewPost. By default you can find it in App/Actions folder.

Sample action file generated with some logic added as below:

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.
    }
}

You can also use dependency injection (DI) on the handle method.

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

You can totally remove the rules method if you are not using it or just leave it as is.

Now that you've created your action, you can call it in few ways as below:

Using plain object

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

$createNewPost->dispatch();

Using static method

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

Using invokable

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

Credits

License

MIT. Please see the license file for more information.