📦 Marketplace⭐ GitHub
API Referencev2.0

Template Engine, Events, Cache & Services


Table of Contents


MLView (Template Engine)

MonkeysLegion\Template\MLView

Blade-like template engine with components, streaming, and PSR-16 caching.

Core Methods

MethodSignatureReturnsDescription
render()(string $name, array $data = [])stringRender template to HTML
make()(string $name, array $data = [])ViewDataDeferred rendering object
renderString()(string $template, array $data = [])stringCompile and render inline template
stream()(string $name, array $data = [])GeneratorStreaming render (chunks)
test()(string $name, array $data = [])TestViewTesting entry point

Shared Data

MethodSignatureDescription
share()(string $key, mixed $value): voidShare data across all views
getShared()(): arrayGet all shared data

View Composers

MethodSignatureDescription
composer()(string|array $views, callable $cb): voidRegister composer for view patterns
rendering()(callable $listener): voidBefore-render listener
rendered()(callable $listener): voidAfter-render listener

Extensibility

MethodSignatureDescription
addDirective()(string $name, callable $handler): voidCustom template directive
addFilter()(string $name, callable $handler): voidCustom output filter
component()(string $name, callable $fn): voidRegister function component
addNamespace()(string $ns, string $hint): voidRegister namespaced view path
addViewPath()(string $path): voidAdd view search path
prependViewPath()(string $path): voidPrepend view search path
setTheme()(string $name, ?string $basePath): voidActivate theme
clearCache()(): voidClear compiled template cache

Template Directives Quick Reference

DirectiveUsage
{{ $var }}Escaped output (htmlspecialchars)
{!! $html !!}Raw HTML output
@extends('layout')Inherit from layout
@section('name') ... @endsectionDefine content section
@yield('name', 'default')Output section
@if / @elseif / @else / @endifConditionals
@foreach($items as $item) / @endforeachLoop
@for / @endforFor loop
@while / @endwhileWhile loop
@isset($var) / @endissetIsset check
@empty($var) / @endemptyEmpty check
@env('dev') / @endenvEnvironment check
@include('partial')Include sub-template
@push('scripts') / @endpushPush to stack
@stack('scripts')Render stack
@php / @endphpRaw PHP block
{{-- comment --}}Template comment (stripped)
<x-component prop="val" />Render component

EventDispatcher

MonkeysLegion\Events\EventDispatcher implements Psr\EventDispatcher\EventDispatcherInterface

PSR-14 dispatcher with interceptor pipeline, metrics, and event store.

Properties

PropertyTypeDescription
$totalDispatchesintTotal dispatches counter (PHP 8.4 hook)

Constructor

ParamTypeDescription
$providerListenerProviderListener provider
$store?EventStoreInterfaceOptional event store for recording
$safeModeboolCatch listener exceptions (default: false)

Methods

MethodSignatureReturnsDescription
dispatch()(object $event)objectPSR-14 dispatch, returns event
dispatchWithResult()(object $event)DispatchResultDispatch with full metrics
dispatchBatch()(array $events)list<DispatchResult>Dispatch multiple events
addInterceptor()(InterceptorInterface $i): voidGlobal interceptor
getProvider()()ListenerProviderAccess listener provider

Event Attributes

AttributeTargetDescription
#[Listener(EventClass::class, priority: 10)]Class/MethodRegister listener
#[Subscriber]ClassRegister event subscriber
#[BeforeEvent(EventClass::class)]MethodBefore-event interceptor
#[AfterEvent(EventClass::class)]MethodAfter-event interceptor
#[ListenWhen(method: 'shouldHandle')]MethodConditional listener

Event Contracts

InterfaceDescription
ShouldQueueDispatch listener via queue
ShouldBroadcastBroadcast event to WebSocket channels

DispatchResult

final readonly class DispatchResult {
    public object $event;
    public int $listenersInvoked;
    public float $durationMs;
    public bool $stopped;
    public array $errors;
}

CacheManager

MonkeysLegion\Cache\CacheManager

PSR-16 compatible cache with multiple stores and tagged cache support.

Methods

MethodSignatureReturnsDescription
get()(string $key, mixed $default = null)mixedRetrieve cached value
set()(string $key, mixed $value, int|DateInterval $ttl = null)boolStore value
has()(string $key)boolCheck key exists
delete()(string $key)boolDelete key
clear()()boolClear entire cache
getMultiple()(iterable $keys, mixed $default = null)iterableBatch get
setMultiple()(iterable $values, int $ttl = null)boolBatch set
deleteMultiple()(iterable $keys)boolBatch delete
tags()(string|array $tags)TaggedCacheTagged cache instance
store()(string $name)CacheStoreAccess specific store
remember()(string $key, int $ttl, Closure $cb)mixedGet or compute and cache
forget()(string $key)boolAlias for delete()

Stores

StoreConfigDescription
FileStoreCACHE_DRIVER=fileFilesystem cache
RedisStoreCACHE_DRIVER=redisRedis cache
MemcachedStoreCACHE_DRIVER=memcachedMemcached
ArrayStoreIn-memory (testing)

Mailer

MonkeysLegion\Mail\Mailer

Email sending with multiple transports and template support.

Methods

MethodSignatureReturnsDescription
send()(Mailable $mailable)voidSend a mailable
raw()(string $text, Closure $cb)voidSend raw text email
to()(string|array $address)PendingMailSet recipient
queue()(Mailable $mailable)voidQueue for async sending

Message Builder

$message = (new Message())
    ->from('noreply@example.com', 'App')
    ->to('user@example.com')
    ->cc('admin@example.com')
    ->bcc('archive@example.com')
    ->replyTo('support@example.com')
    ->subject('Welcome!')
    ->html('<h1>Hello</h1>')
    ->text('Hello')
    ->attach('/path/to/file.pdf')
    ->priority(1);

Transports

TransportConfigDescription
SmtpTransportMAIL_DRIVER=smtpSMTP delivery
MailgunTransportMAIL_DRIVER=mailgunMailgun API
SendmailTransportMAIL_DRIVER=sendmailLocal sendmail
NullTransportMAIL_DRIVER=nullDiscard (testing)
MonkeysMailTransportMAIL_DRIVER=monkeysmailMonkeysCloud service

Queue

MonkeysLegion\Queue\Contracts\QueueInterface

Background job processing with multiple drivers.

QueueDispatcher Methods

MethodSignatureDescription
dispatch()(JobInterface $job): voidPush job to queue
dispatchSync()(JobInterface $job): voidExecute job immediately
dispatchAfterResponse()(JobInterface $job): voidQueue after HTTP response
chain()(array $jobs): PendingChainChain jobs sequentially

Job Interface

interface JobInterface {
    public function handle(): void;
    public function failed(\Throwable $e): void;
    public function tries(): int;
    public function timeout(): int;
    public function retryAfter(): int;
}

Queue Drivers

DriverConfigDescription
syncQUEUE_CONNECTION=syncExecute immediately (dev)
databaseQUEUE_CONNECTION=databaseDatabase-backed queue
redisQUEUE_CONNECTION=redisRedis-backed queue

CLI Commands

CommandDescription
php vendor/bin/ml queue:workStart queue worker
php vendor/bin/ml queue:failedList failed jobs
php vendor/bin/ml queue:retryRetry failed jobs
php vendor/bin/ml queue:flushFlush failed jobs
php vendor/bin/ml queue:clearClear pending jobs
php vendor/bin/ml queue:statsQueue statistics

Schedule

MonkeysLegion\Schedule

Cron-based task scheduling.

// In a ScheduleProvider
$schedule->command('queue:work --stop-when-empty')->everyMinute();
$schedule->call(fn() => $this->cleanup())->daily()->at('03:00');
$schedule->job(new PruneExpiredTokens())->hourly();

Frequency Methods

MethodDescription
everyMinute()Run every minute
everyFiveMinutes()Run every 5 minutes
everyFifteenMinutes()Run every 15 minutes
everyThirtyMinutes()Run every 30 minutes
hourly()Run every hour
daily()Run daily at midnight
dailyAt(string $time)Run daily at specific time
weekly()Run weekly
monthly()Run monthly
cron(string $expression)Custom cron expression

I18n

MonkeysLegion\I18n

Internationalization support with locale detection middleware.

Key Methods

MethodSignatureReturnsDescription
trans()(string $key, array $replace = [], ?string $locale = null)stringTranslate key
setLocale()(string $locale): voidSet current locale
getLocale()()stringGet current locale

Files (Storage)

Configured in config/files.mlc. File upload and storage abstraction.

Key Settings

KeyDefaultDescription
files.default_disklocalActive storage disk
files.max_bytes20971520 (20MB)Max upload size
files.mime_allow["image/jpeg","image/png","image/webp","application/pdf"]Allowed MIME types

Disk Configuration

DiskDescription
localLocal filesystem (public/files/)
s3AWS S3 bucket
gcsGoogle Cloud Storage

Logger

Configured in config/logging.mlc. PSR-3 compatible logging.

Log Levels (PSR-3)

debuginfonoticewarningerrorcriticalalertemergency

Channels

ChannelDriverDescription
stackstackCombines daily + console
dailyfileDate-rotated log files
singlefileSingle log file
consoleconsoleStdout output
emergencyfileEmergency-only log
nullnullDiscard all logs

MLC Config

MonkeysLegion\Mlc\Config

HOCON-like configuration format parser (.mlc files).

Syntax Reference

# Comment
app {
    name = "My App"              # String
    debug = true                  # Boolean
    port = 8000                   # Integer
    env = ${APP_ENV:production}   # Env var with default
    hosts = ["a.com", "b.com"]   # Array
    nested {                      # Nested block
        key = "value"
    }
}

Access Pattern

$config = $container->get(MlcConfig::class);
$appName = $config->get('app.name');         // Dot notation
$debug   = $config->get('app.debug', false); // With default
$hosts   = $config->get('app.hosts');        // Returns array

DI Attributes

AttributeTargetDescription
#[Singleton]ClassRegister as single-instance in container
#[Provider]ClassMark as service provider (auto-discovered)
#[BootAfter(OtherProvider::class)]ClassProvider ordering

End of API Reference


Quick Navigation

PartDocumentContents
1Core, HTTP & RoutingApplication, Response, Route, Middleware
2Entity, Query & RepositoryEntity Attributes, QueryBuilder, EntityRepository
3Auth, Session & ValidationAuthService, JWT, Session, Validation, RBAC
4This documentTemplate, Events, Cache, Mail, Queue, Schedule, I18n, Files, Logger, Config