Maginium
Docs
Docs
  • Welcome
  • Getting Started
    • Quickstart
    • Installation
    • Structure
  • The Basics
    • Concurrency
    • 🔤Strings
    • ⚙️Actions
    • 🗃️Cache
    • 🗂️Collections
    • 🔲Component
    • ⚙️Config
    • 💬Console
    • 🗃️Database
      • Overview
      • Eloquent
      • Seeder
      • Migration
      • Models
      • Factories
      • Schemas
      • Traits
      • Concerns
    • 🛅Container
    • 🔠Enum
    • 📦Event
    • 📝Log
    • 🔢Pagination
    • 💬Prompts
    • 🌐Request
    • 📡Response
    • ⚡Redis
    • 📏Resize
    • 🔌Serializer
      • Json
      • Serializer
      • Closure Serializer
    • 🔑Uuid
    • 👤Avatar
    • 🔐Hashing
    • 📤Dto
      • Overview
      • Attributes
    • 🌍Locale
    • 🔗Token
      • Api Keys
      • Admin Token
      • Customer Token
    • 🕘Message Queue
    • 🖼️Media
    • Helpers
    • 📜Crud
      • Filters and Sorts
        • introduction
        • Basic Usage
        • JS Examples
          • Available Methods
          • Sorts
          • Filters
        • Rename Fields
        • Relation Fields
        • Changing Params Source
        • Allowed Fields
        • Queries and javascript examples
        • Sort null values last
        • Restrict
        • Custom Filters
  • Commerce Modules
    • API Key Module
    • Auth Module
    • Cart Module
    • Customer Module
    • Inventory Module
    • Fulfillment Module
    • Order Module
    • Payment Module
    • Pricing Module
    • Product Module
    • Promotion Module
    • User Module
  • SDKs and Tools
    • create-maginium-app
    • Maginium CLI
    • JS SDK
    • Storefront Starter
Powered by GitBook
On this page
  • Introduction
  • AsObject
  • AsController
  • #Methods used
  1. The Basics

Actions

PreviousStringsNextCache

Last updated 4 months ago

Classes that take care of one specific task.

This package introduces a new way of organizing the logic of your Maginium applications by focusing on the actions your applications provide.

Instead of creating controllers, jobs, listeners, and so on, it allows you to create a PHP class that handles a specific task and run that class as anything you want.

make

Resolves the action from the container.

MyAction::make();

// Equivalent to:
app(MyAction::class);

run

Resolves and executes the action.

MyAction::run($someArguments);

// Equivalent to:
MyAction::make()->handle($someArguments);

Resolves and executes the action if the condition is met.

MyAction::runIf(true, $someArguments);

Resolves and executes the action if some condition is not met.

MyAction::runUnless(false, $someArguments);

Executes the action by delegating immediately to the handle method.

$action($someArguments);

// Equivalent to:
$action->handle($someArguments);

Whilst this method is not used, it has to be defined on the action to register the action as an invokable controller. When missing, Maginium will throw an exception warning us that we're trying to register a class as an invokable controller without the __invoke method. The truth is, the controller will be an instance of ControllerDecorator but the framework doesn't know that yet.

protected static function makeInvokable($action)
{
    if (! method_exists($action, '__invoke')) {
        throw new UnexpectedValueException("Invalid controller action: [{$action}].");
    }

    return $action.'@__invoke';
}
class MyAction
{
    use AsAction {
        __invoke as protected invokeFromMaginiumActions;
    }

    public function __invoke()
    {
        // ...
    }
}

Lists all methods recognized and used by the ControllerDecorator

It is called when used as an invokable controller. Uses the handle method directly when no asController method exists.

public function asController(User $user, Request $request): Response
{
    $article = $this->handle(
        $user,
        $request->get('title'),
        $request->get('body')
    );

    return redirect()->route('articles.show', [$article]);
}

Called after the asController method when the request expects JSON. The first argument is the return value of the asController method and the second argument is the request itself.

public function jsonResponse(Article $article, Request $request): ArticleResource
{
    return new ArticleResource($article);
}

Called after the asController method when the request expects HTML. The first argument is the return value of the asController method and the second argument is the request itself.

public function htmlResponse(Article $article, Request $request): Response
{
    return redirect()->route('articles.show', [$article]);
}

Adds controller middleware directly in the action.

public function getControllerMiddleware(): array
{
    return ['auth', MyCustomMiddleware::class];
}

Called right before authorization and validation is resolved.

public function prepareForValidation(ActionRequest $request): void
{
    $request->merge(['some' => 'additional data']);
}

Defines authorization logic for the controller.

public function authorize(ActionRequest $request): bool
{
    return $request->user()->role === 'author';
}

You may also return gate responses instead of booleans.

use Illuminate\Auth\Access\Response;

public function authorize(ActionRequest $request): Response
{
    if ($request->user()->role !== 'author') {
        return Response::deny('You must be an author to create a new article.');
    }

    return Response::allow();
}

Provides the validation rules for the controller.

public function rules(): array
{
    return [
        'title' => ['required', 'min:8'],
        'body' => ['required', IsValidMarkdown::class],
    ];
}

Adds custom validation logic to the existing validator.

use Illuminate\Validation\Validator;

public function withValidator(Validator $validator, ActionRequest $request): void
{
    $validator->after(function (Validator $validator) use ($request) {
        if (! Hash::check($request->get('current_password'), $request->user()->password)) {
            $validator->errors()->add('current_password', 'Wrong password.');
        }
    });
}

Adds an after callback to the existing validator. The example below is equivalent to the example provided in the withValidator method.

use Illuminate\Validation\Validator;

public function afterValidator(Validator $validator, ActionRequest $request): void
{
    if (! Hash::check($request->get('current_password'), $request->user()->password)) {
        $validator->errors()->add('current_password', 'Wrong password.');
    }
}

DefineDefines your validator instead of the default one generated using rules, withValidator, etc.

use Illuminate\Validation\Factory;
use Illuminate\Validation\Validator;

public function getValidator(Factory $factory, ActionRequest $request): Validator
{
    return $factory->make($request->only('title', 'body'), [
        'title' => ['required', 'min:8'],
        'body' => ['required', IsValidMarkdown::class],
    ]);
}

Defines the data that should be used for validation. Defaults to: $request->all().

public function getValidationData(ActionRequest $request): array
{
    return $request->all();
}

Customize the messages of your validation rules.

public function getValidationMessages(): array
{
    return [
        'title.required' => 'Looks like you forgot the title.',
        'body.required' => 'Is that really all you have to say?',
    ];
}

Provides some human-friendly mapping to your request attributes.

public function getValidationAttributes(): array
{
    return [
        'title' => 'headline',
        'body' => 'content',
    ];
}

Customises the redirect URL when validation fails. Defaults to redirecting back to the previous page.

public function getValidationRedirect(UrlGenerator $url): string
{
    return $url->to('/my-custom-redirect-url');
}

Customises the validator's error bag when validation fails. Defaults to: default.

public function getValidationErrorBag(): string
{
    return 'my_custom_error_bag';
}

Overrides the validation failure altogether. Defaults to: ValidationException.

public function getValidationFailure(): void
{
    throw new MyCustomValidationException();
}

Overrides the authorization failure. Defaults to: AuthorizationException.

public function getAuthorizationFailure(): void
{
    throw new MyCustomAuthorizationException();
}

runIf

runUnless

__invoke

If you need to use the __invoke method for something else, you may with anything you want. The only requirement is that a __invoke method has to exist.

Methods used

asController

jsonResponse

htmlResponse

getControllerMiddleware

prepareForValidation

authorize

rules

withValidator

afterValidator

getValidator

getValidationData

getValidationMessages

getValidationAttributes

getValidationRedirect

getValidationErrorBag

getValidationFailure

getAuthorizationFailure

⚙️
#
#
#
override it (opens a new window)
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
Introduction
AsObject
As Controller
Introduction
AsObject
AsController