PHP code example of bamise / framework

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

    

bamise / framework example snippets


use Bamise\Contract\Domain\ResourceDefinitionInterface;
use Bamise\Contract\Enum\OperationType;

final class PostDefinition implements ResourceDefinitionInterface
{
    public function resourceName(): string  { return 'posts'; }
    public function primaryKey(): string    { return 'id'; }
    public function fillable(): array       { return ['title', 'body', 'author_id']; }
    public function guarded(): array        { return ['id', 'created_at']; }

    public function allowedOperations(): array
    {
        return [
            OperationType::Create,
            OperationType::Read,
            OperationType::Update,
            OperationType::Delete,
        ];
    }
}

use Bamise\Infrastructure\Persistence\PDO\PdoConnection;
use Bamise\Infrastructure\Persistence\PDO\ConnectionConfig;
use Bamise\Infrastructure\Persistence\PDO\PdoRepository;
use Bamise\Contract\Enum\DatabaseDriver;

$config = new ConnectionConfig(
    driver: DatabaseDriver::Mysql,
    dsn: 'mysql:host=127.0.0.1;dbname=myapp',
    user: 'root',
    password: 'secret',
);

$connection  = PdoConnection::fromConfig($config);
$definition  = new PostDefinition();
$repository  = new PdoRepository($connection, $definition);

use Bamise\Application\Registry\ResourceRegistry;
use Bamise\Application\Registry\RepositoryResolver;
use Bamise\Application\CrudApplication;

$resources  = new ResourceRegistry();
$resolver   = new RepositoryResolver();

$resources->register($definition);
$resolver->register('posts', $repository);

$app = new CrudApplication($resources, $resolver, /* ...middlewares, strategies... */);

use Bamise\Contract\Http\CrudRequestInterface;

// $request is any object implementing CrudRequestInterface
$response = $app->handle($request);

echo $response->status();  // 200, 422, 403 …
echo json_encode($response->data());

use Bamise\Infrastructure\Security\Csrf\CsrfGuard;
use Bamise\Infrastructure\Cache\InMemoryCache;

$cache = new InMemoryCache();
$guard = new CsrfGuard($cache, ttl: 3600);

$token = $guard->generate('session-id');
$guard->validate('session-id', $token); // throws on mismatch

use Bamise\Infrastructure\Security\RateLimit\CacheRateLimiter;

$limiter = new CacheRateLimiter($cache, maxAttempts: 60, windowSeconds: 60);
// Used automatically by RateLimitMiddleware when registered in the pipeline

use Bamise\Infrastructure\Security\Signing\HmacRequestSigner;

$signer    = new HmacRequestSigner(secret: getenv('HMAC_SECRET'));
$signature = $signer->sign(['resource' => 'posts', 'action' => 'create']);
// Attach as X-Signature header; verify incoming requests with $signer->verify($request)

use Bamise\Infrastructure\Security\Policy\CallablePolicy;
use Bamise\Domain\Policy\PolicyEvaluator;

$policy = new CallablePolicy(
    static fn (OperationType $op, ?object $subject, string $resource): bool =>
        $subject !== null && in_array('admin', $subject->roles ?? [], true),
);

$evaluator = new PolicyEvaluator([$policy]);
$allowed   = $evaluator->evaluate(OperationType::Delete, $subject, 'posts');

use Bamise\Contract\Event\DomainEventInterface;
use Bamise\Infrastructure\Event\EventDispatcher;
use Bamise\Infrastructure\Event\ListenerRegistry;

$registry   = new ListenerRegistry();
$dispatcher = new EventDispatcher($registry);

// Register a listener for all BeforeCrud events
$registry->register(
    eventClass: \Bamise\Domain\Event\BeforeCrudEvent::class,
    listener:   static function (DomainEventInterface $event): void {
        // inspect $event->context(), $event->payload() …
    },
);

use Bamise\Contract\Event\EventSubscriberInterface;

final class AuditSubscriber implements EventSubscriberInterface
{
    public static function subscribedEvents(): array
    {
        return [
            \Bamise\Domain\Event\AfterCrudEvent::class => [['onAfterCrud', 10]],
        ];
    }

    public function onAfterCrud(DomainEventInterface $event): void
    {
        // log to your audit trail
    }
}

// Register via SubscriberLoader
$loader = new \Bamise\Infrastructure\Event\SubscriberLoader($registry);
$loader->load(new AuditSubscriber());

// Implement QueuePortInterface and pass to AsyncEventDispatcher
$asyncDispatcher = new \Bamise\Infrastructure\Event\AsyncEventDispatcher($queue, $encoder);
bash
composer cs-check   # Check without modifying
composer cs-fix     # Fix in place
# Config: .php-cs-fixer.dist.php (@PER-CS2.0 + @PHP84Migration)