An open API service indexing awesome lists of open source software.

https://github.com/kirschbaum-development/laravel-actions


https://github.com/kirschbaum-development/laravel-actions

hacktoberfest

Last synced: about 1 year ago
JSON representation

Awesome Lists containing this project

README

          

[//]: # (![Mail Intercept banner](screenshots/banner.jpg))

# Laravel Actions
### A package for handling simple actions with eventing.

[![Latest Version on Packagist](https://img.shields.io/packagist/v/kirschbaum-development/laravel-actions)](https://packagist.org/packages/kirschbaum-development/laravel-actions)
[![Total Downloads](https://img.shields.io/packagist/dt/kirschbaum-development/laravel-actions)](https://packagist.org/packages/kirschbaum-development/laravel-actions)
[![Actions Status](https://github.com/kirschbaum-development/laravel-actions/workflows/CI/badge.svg)](https://github.com/kirschbaum-development/laravel-actions/actions)

Laravel Actions are simple job-like classes that don't interact with the queue. Actions are great to leverage when you have some simple functionality that you need to reuse.

But why would you want to use Actions you ask? Actions are great when you have small bits of code that you want to extract into small, testable classes. Actions can also take the place of queued jobs when you don't want or need that kind of power, or if you need the results of the code right now.

But the real power is with eventing.

This package exposes two events during your Action:
- Before the Action begins
- After the Action completes

The special sauce here is that you get to tell the Action which events you want triggered!

## Requirements

| PHP Version | Laravel Actions Version |
|--------------|-------------------------|
| `^6.0, ^7.0` | `^0.1.0` |
| `^8.0` | `^0.2.0` |

## Installation

```bash
composer require kirschbaum-development/laravel-actions
```

## Creating and Preparing the Action

Create a new Action with artisan command:

```bash
php artisan make:action ChuckNorris
```

This will create a new Action class at `app/Actions/ChuckNorris.php`. You are, of course, free to move the action wherever you want. Just make sure you update the namespace!

There are two public properties ready for your events: `$before` and `$after`. You can use one or both of these, and you can remove either of them if you don't use them in your Action class.

```php
/**
* Event to dispatch before action starts.
*
* @var string
*/
public $before = ChuckNorrisWillBlowYourMind::class;

/**
* Event to dispatch after action completes.
*
* @var string
*/
public $after = ChuckNorrisBlewYourMind::class;
```

Next place your required arguments within the `__construct()` method and your Action code within the `__invoke()` method. You are free to return anything you might need from the invokeable method. Now we're ready to use the Action!

```php
/**
* Create a new action instance.
*
* @return void
*/
public function __construct()
{
// Pass any arguments you need.
}

/**
* Execute the action.
*
* @return mixed
*/
public function __invoke()
{
// Handle your action here.
}
```

## Usage

There are two different ways we can call our newly created Action.

### From the Action

We can call one of three methods on the Action itself as long as the class is using the `CanAct` trait.

```php
ChuckNorris::act($data);
ChuckNorris::actWhen($isChuckNorrisMighty, $data);
ChuckNorris::actUnless($isChuckNorrisPuny, $data);
```

The `$data` is passed into the Action's constructor. You can pass as many arguments as needed in your use case.

The second two methods, `actWhen` and `actUnless` require a condition as the first variable. These work like other Laravel methods such as `throw_if()` and `throw_unless()`. Finally, you can pass as many arguments as needed for your Action after the condition.

### Facade

The package also has a facade. Here's the syntax:

```php
use Kirschbaum\Actions\Facades\Action;

Action::act(ChuckNorris::class, $data);
Action::actWhen($isChuckNorrisMighty, ChuckNorris::class, $data);
Action::actUnless($isChuckNorrisPuny, ChuckNorris::class, $data);
```

The usage is nearly identical to calling the methods directly on the Action as mentioned in the section above. The benefit here is that you can easily test actions using `Action::shouldReceive('act')`, `Action::shouldReceive('actWhen')` or `Action::shouldReceive('actUnless')`.

### Helpers

The package also has a few handy helpers to get Chuck in action. Here's the syntax:

```php
act(ChuckNorris::class, $data);
act_when($isChuckNorrisMighty, ChuckNorris::class, $data);
act_unless($isChuckNorrisPuny, ChuckNorris::class, $data);
```

### Dependency Injection

You can even inject Actions as a dependencies inside your application!

```php
use Kirschbaum\Actions\Action;

public function index (Action $action)
{
$action->act(ChuckNorris::class, $data);
$action->actWhen($isChuckNorrisMighty, ChuckNorris::class, $data);
$action->actUnless($isChuckNorrisPuny, ChuckNorris::class, $data);
}
```

## Macros

There are times when you may want to add something extra to your actions. We can leverage macros for this!

Here is an example were we are leveraging Inertia's defer functionality directly on our action. The macro then just calls `act()` on the action class when the deferred prop is requested!

```php
// In your service provider
Action::macro('defer', function($action, ...$arguments) {
return Inertia::defer(fn () => $action::act(...$arguments));
});

// In your controller
return Inertia::render('Users/Index')
->with('users', GetUsers::defer());
```

Note how the originating class is passed into the macro function as the first parameter. This is very important, otherwise the macro will be unaware of which action you are actually running as macros are technically run on the parent action class. You are also free to do what you want regarding the subsequent $arguments, but it is considered best practice to pack/unpack the arguments with the spread operator to ensure the actions are as flexible as possible.

Also take note the `defer()` is defined on the `Kirschbaum\Actions\Action` class, not on the `GetUsers` action class. Individual actions are not macroable in and of themselves. The macro `defer()` will also be available to every action in your application, not just the `GetUsers` action!

Before and after events will not be fired when using macros. They will get fired however if you use an action's `act()`, `actWhen()`, or `actUnless()` methods with the macro function.

## Handling Failures

We all know Chuck Norris isn't going to fail us, but he isn't the only one using this... Handling failures is pretty easy with Actions. Out of the box, any exceptions thrown by your Action classes get handled by Laravel's exception handler. If you'd rather implement your own logic during a failure, add a `failed()` method to your Action. It's that easy! You can return data from your `failed()` method if you choose as well.

```php
/**
* Handle failure of the action.
*
* @throws Throwable
*
* @return mixed
*/
public function failed(Throwable $exception)
{
event(new VanDammeFailedEvent);
}
```

Hashtag #BAM!

### Custom Exceptions

Another option for handling failures is to tell the Action to throw its own exception. If you don't need the extra overhead of writing your own `failed()` method, you can just tell your Action to throw a custom exception. It's as simple as just defining the exception you want thrown from the Action.

```php
/**
* Event to dispatch if action throws an exception.
*
* @var string
*/
public $exception = SeagalFailedException::class;
```

## Auto-Discovery and Configuration

Out of the box, actions are automatically discovered and bound to Laravel's container, which allows for easier testing of your actions. If you need to add a custom path if you are placing your actions somewhere other than `app/Actions`, make sure to publish the configs.

```bash
php artisan vendor:publish --tag laravel-actions
```

If you want to disable auto-discovery, publish the config and return an empty array from the `paths` key.

```php
return [
'paths' => [],
];
```

## Testing

Have no fear. Testing all of this is very straightforward. There are two approaches to testing built in.

### Testing Facades

If you are using Facades to implement your Actions, you can use the standard `shouldReceive()` method directly from the Facade.

```php
use Kirschbaum\Actions\Facades\Action;

Action::shouldReceive('act')
->once()
->andReturnTrue();
```

### Mocking

If you are using helpers, the `CanAct` trait, or dependency injection, you can easily mock the `Action` class with Laravel's mocking tools.

```php
use Kirschbaum\Actions\Action;

$this->mock(Action::class, function ($mock) {
$mock->shouldReceive('act')
->once()
->andReturnTrue();
});
```

Because actions are bound into Laravel's container by default, you can test specific actions as well.

```php
use App\Actions\ChuckNorris;

$this->mock(ChuckNorris::class, function ($mock) {
$mock->shouldReceive('act')
->once()
->andReturnTrue();
});
```

## Last thoughts

If for some reason you'd prefer not to use the cool Eventing system, Facades, Mocking, etc., that's fine. Just call your Action like this:

```php
new ChuckNorris($data);
```

This will bypass all the magic and call the invoke method automagically, letting Chuck do his thing without anyone knowing, but why? ;)

## Changelog

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

### Security

If you discover any security related issues, please email brandon@kirschbaumdevelopment.com or nathan@kirschbaumdevelopment.com instead of using the issue tracker.

## Credits

- [Brandon Ferens](https://github.com/brandonferens)
- Inspired in part by [Luke Downing's](https://github.com/lukeraymonddowning) Laracon Online Winter '22 [talk](https://www.youtube.com/watch?v=0Rq-yHAwYjQ&t=1678s).

## Sponsorship

Development of this package is sponsored by Kirschbaum, a developer driven company focused on problem solving, team building, and community. Learn more [about us](https://kirschbaumdevelopment.com) or [join us](https://careers.kirschbaumdevelopment.com)!

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.