PHP code example of rcrdortiz / axpecto

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

    

rcrdortiz / axpecto example snippets




$list = listOf(1, 2, 3, 4, 5);

$filtered = $list
    ->map(fn($i) => $i * 2)
    ->filter(fn($i) => $i > 5)
    ->toArray(); // [6, 8, 10]

class User {
    public function __construct(
        public readonly int $id,
        public readonly string $name
    ) {}
}

// Assume this is a list of User objects fetched from the user repository
$users = listOf(
    new User(1, 'Alice'),
    new User(2, 'Bob'),
    new User(3, 'Charlie')
);

$names = $users
    ->map(fn($u) => $u->name)
    ->join(', ');

// "Alice, Bob, Charlie"

$orders = listOf(150, 20, 35, 80, 200);

$highValueOrders = $orders
    ->filter(fn($amount) => $amount >= 100);

// [150, 200]

$logs = listOf('info', 'debug', 'error');

// maybe() allows optional side effects or context-aware logic only when the list contains items
$logs->maybe(function(Klist $items) {
    $logger->log($items);
    $stats->bump('logs', $items->count());
    echo "done logging " . $items->count() . " items";
});

// done logging 3 items

// Now, let's say we have an empty list
$logs = emptyList();

// When there are no results, the callback is not executed
$logs->maybe(function(Klist $items) {
    echo "This doesn't get echoed";
});

$orders = listOf(100, 250, 90, 300);

$allAbove50 = $orders->all(fn($amount) => $amount > 50); // true
$anyAbove500 = $orders->any(fn($amount) => $amount > 500); // false

if ($orders->any(fn($o) => $o > 100)) {
    echo "User gets free shipping and insurance!";
}

// Traditional PHP
array_filter(array_map(fn($x) => $x * 2, [1, 2, 3, 4]), fn($x) => $x > 5);

// With Axpecto
listOf(1, 2, 3, 4)
    ->map(fn($x) => $x * 2)
    ->filter(fn($x) => $x > 5);

$container = new Container();

$app = $container->get(MyApplication::class);

$container->bind(CacheInterface::class, MyCache::class);
$container->addClassInstance(Logger::class, new CustomLogger());
$container->addValue('api_key', 'abcdef123');

class ReportGenerator {
    public function __construct(
        private LoggerInterface $logger,
        private ReportRepository $repository
    ) {}

    public function generate() {
        $this->logger->info("Generated: " . count($this->repository->getAll()) . " reports");
    }
}

$reporter = $container->get(ReportGenerator::class);

// Generate reports
$reporter->generate();

$container->addValue('site_name', 'MyApp');
$container->bind(MailerInterface::class, SMTPMailer::class);

class WelcomeMailer {
    #[Inject] private string $site_name;
    #[Inject] private MailerInterface $mailer;

    public function send($to) {
        $this->mailer->send($to, "Welcome to {$this->site_name}!");
    }
}

$container->bind(LoggerInterface::class, FileLogger::class);

// Replace with a mock during testing
$container->addClassInstance(LoggerInterface::class, new MockLogger());

#[HtmlOutput(
  path: 'template.php',
  styles: ['main.css'],
  script_data_provider: fn($result) => ['data' => $result],
)]
public function renderDashboard() {
    return [ 'user' => 'Jane' ];
}

#[Repository(entityClass: Customer::class)]
abstract class CustomerRepository {
    public abstract function findByIdGreaterThanAndEmailOrEmailIsNull($id, $email);
}

#[Service]
abstract class ReportService {
    public abstract function generate();
}

class ServiceBuildHandler implements BuildHandler {
    public function intercept(Annotation $annotation, BuildContext $context): void {
        if (! $annotation instanceof Service || $annotation->getAnnotatedMethod() !== null) return;

        foreach ($context->getAbstractMethods() as $method) {
            $context->addMethod(
                $method->getName(),
                "public function {$method->getName()}()",
                "// Auto-generated service method implementation"
            );
        }
    }
}

#[Cacheable(ttl: 60)]
public function getLatestPosts() {
    return $this->query->fetch();
}

class CacheableHandler implements MethodExecutionHandler {
    public function intercept(MethodExecutionContext $ctx): mixed {
        $key = md5($ctx->className . $ctx->methodName . serialize($ctx->arguments));
        $cache = new SimpleCache();

        if ($cache->has($key)) {
            return $cache->get($key);
        }

        $result = $ctx->proceed();
        $cache->set($key, $result, $ctx->getAnnotation()->ttl);

        return $result;
    }
}

#[Logged]
public function processOrder($orderId) {
    // Core logic here
}

class LoggedHandler implements MethodExecutionHandler {
    public function intercept(MethodExecutionContext $ctx): mixed {
        error_log("Entering {$ctx->className}::{$ctx->methodName}");
        $result = $ctx->proceed();
        error_log("Exiting {$ctx->className}::{$ctx->methodName}");
        return $result;
    }
}

#[Repository(entityClass: Customer::class)]
abstract class CustomerRepository {
    public abstract function findByEmail(string $email);
    public abstract function findByUsernameOrEmail(string $username, string $email);
}
// This defines a CustomerRepository where the methods will be built automatically. When you call:
$repo = $container->get(CustomerRepository::class);
$customer = $repo->findByEmail('[email protected]');

// Example generated logic for a method like:
public abstract function findByIdGreaterThanAndEmailOrEmailIsNull($id, $email);

// ...will result in a criteria similar to:
$criteria->addCondition('id', $id, Operator::GREATER_THAN);
$criteria->addCondition('email', $email, Operator::EQUALS, LogicOperator::OR);
$criteria->addCondition('email', null, Operator::IS_NULL, LogicOperator::OR);

#[Entity(storage: MysqlPersistenceStrategy::class, table: 'customer')]
class Customer {
    public function __construct(
        #[Id(autoIncrement: true)]
        public ?int $id,
        #[UniqueNotNull]
        public string $username,
        #[UniqueNotNull]
        public string $email,
        #[Column(isNullable: true)]
        public string $password,
        #[Timestamp]
        public DateTime $createdAt,
        #[Timestamp(onUpdate: Column::CURRENT_TIMESTAMP)]
        public DateTime $updatedAt,
        #[UniqueNotNull]
        public string $displayName,
    ) {}
}

#[Validate]
#[Authorize(role: 'admin')]
public function deleteUser($userId) {
    // Executed only after validation + security checks
}