PHP code example of sammakescode / business-rules

1. Go to this page and download the library: Download sammakescode/business-rules 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/ */

    

sammakescode / business-rules example snippets




namespace App\BusinessRules;

use SamMakesCode\BusinessRules\BusinessRule;
use App\Models\User;

class UserCanPost implements BusinessRule
{
    public function __construct(
        public readonly User $user,  
    ) {
    
    public function isSatisfied(): bool
    {
        return !$this->user->isBanned && $this->user->isAuthor();
    }
    
    public function getFailureMessage(): string
    {
        return 'This user isn\'t allowed to post!';
    }
}




namespace App\Services;

use SamMakesCode\BusinessRules\BusinessRules;
use App\Models\User;

class PostsService
{
    use BusinessRules;

    public function createPost(
        User $author,
        string $title,
        string $slug,
        string $body,    
    ): Post {
        $this->checkBusinessRules([
            new UserCanPost($user),
            // Additional business rules, if you want
        ]);
        
        // Create a post
    }
}


// In some controller...

try {
    $postsService->createPost($user, 'Title', 'slug', 'The body of a post')
} catch (BusinessRulesNotSatisfied $exception) {
    return redirect()->back()->with([
        'errors' => $exception->getFailingRuleMessages(),
    ]);
}