PHP code example of laraditz / action

1. Go to this page and download the library: Download laraditz/action library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

laraditz / action example snippets


namespace App\Actions;

use App\Models\Post;
use Laraditz\Action\Action;

class CreateNewPost extends Action
{
    public function __construct(
        public string $title,
        public string $body,
    ) {}

    public function handle(): Post
    {
        return Post::create($this->data());
    }
}

$post = (new CreateNewPost(title: 'Hello', body: 'World'))->run();

$post = CreateNewPost::run(title: 'Hello', body: 'World');

namespace App\Actions;

use App\Mail\PostCreated;
use App\Models\Post;
use Illuminate\Contracts\Mail\Mailer;
use Laraditz\Action\Action;

class PublishPost extends Action
{
    public function __construct(
        public string $title,
        public string $body,
        public string $authorEmail,
    ) {}

    public function handle(Mailer $mailer): Post
    {
        $post = Post::create($this->data());

        $mailer->to($this->authorEmail)->send(new PostCreated($post));

        return $post;
    }
}

// $mailer is resolved from the container automatically
PublishPost::run(
    title: 'My Post',
    body: 'Content here',
    authorEmail: '[email protected]',
);

namespace App\Actions;

use App\Mail\WelcomeEmail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Laraditz\Action\Action;

class SendWelcomeEmail extends Action implements ShouldQueue
{
    use Queueable, InteractsWithQueue, SerializesModels;

    public function __construct(
        public string $email,
        public string $name,
    ) {}

    public function handle(Mailer $mailer): void
    {
        $mailer->to($this->email)->send(new WelcomeEmail($this->name));
    }
}

// Using the base class static dispatch()
SendWelcomeEmail::dispatch(email: '[email protected]', name: 'Alice');

// Using Laravel's global helper
dispatch(new SendWelcomeEmail(email: '[email protected]', name: 'Alice'));

public function handle(): Post
{
    // Returns ['title' => '...', 'body' => '...']
    return Post::create($this->data());
}
bash
php artisan make:action CreateNewPost