Skip to content

Instantly share code, notes, and snippets.

@urameshibr
Created December 18, 2021 05:05
Show Gist options
  • Select an option

  • Save urameshibr/b0c9de09c49f7dd3f742235b55b4a892 to your computer and use it in GitHub Desktop.

Select an option

Save urameshibr/b0c9de09c49f7dd3f742235b55b4a892 to your computer and use it in GitHub Desktop.
PHP Laravel Action Dispatcher with default options (humble example)
<?php
namespace App\Actions;
class ActionService
{
protected array $defaultOptions = [];
/**
* @return array
*/
public function getDefaultOptions(): array
{
return $this->defaultOptions ?? [];
}
}
<?php
namespace App\Providers;
use App\Actions\Shop\Types\ListShopTypesAction;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->bind('list-shop-types-action', ListShopTypesAction::class);
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}
<?php
namespace App\Actions;
final class Dispatch
{
public static function action(string $action, ...$params)
{
$handle = app()->get($action);
$options = [];
$useDefaultOptions = true;
$defaultOptions = $handle->getDefaultOptions();
foreach ($params as $key => &$value) {
if (is_array($value)) {
if ($useDefaultOptions) {
$options[] = array_merge($defaultOptions, $value);
$useDefaultOptions = false;
continue;
}
$options[] = $value;
continue;
}
$options[] = $value;
}
return $handle(...$options);
}
}
<?php
namespace App\Actions\Shop\Types;
use App\Actions\ActionService;
use App\Http\Queries\ShopTypeQuery;
class ListShopTypesAction extends ActionService
{
protected array $defaultOptions = [
'paginate' => false,
'per_page' => 10,
];
public function __invoke(array $options)
{
list('paginate' => $paginate, 'per_page' => $per_page) = $options;
// returns
}
}
<?php
namespace App\Http\Controllers\Master\Shop\Type;
use App\Actions\Dispatch;
use App\Http\Controllers\Controller;
use App\Http\Requests\Master\Shop\Type\ShopTypeRequest;
class ListShopTypesActionController extends Controller
{
public function __invoke(ShopTypeRequest $request): \Illuminate\Http\JsonResponse
{
$data = Dispatch::action('list-shop-types-action', $request->validated());
return response()->json($data);
}
}
// or... can be used with no binds from service provider
// use App\Actions\Shop\Types\ListShopTypesAction;
// Dispatch::action(ListShopTypesAction::class, $request->validated());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment