Članci s tagom #shinobi-apps-framework
-
How I built a PHP framework solo in 18 months: decisions that kept it manageable
18 months building the Shinobi Apps framework solo: zero runtime Composer deps (vendor/ not shipped), 4-prefix autoloader, zero BC policy (framework moves with production needs not arbitrary API stability), addon isolation (CSS/PHP stays in addon folder, not in core), forward-only migrations (no down/rollback), PHPStan level 5 + Psalm taint analysis as global tools. Sustainable for one person = the primary constraint.
-
Public status pages in PHP SaaS: per-tenant, opt-in, no subdomain required
Sonar status page: /sonar/status/{slug} public route (no auth, `minimal` middleware). sonar_tenant_settings.public_status_page_enabled DEFAULT 0 — 404 until opt-in (slug enumeration defence). sonar_monitors.is_public per-monitor gate. 90-day uptime calendar bucketed in PHP per-monitor-per-day (up/degraded/down). M6: raw probe summary sanitised to type-based label (internal IP leak prevention). Overall status: critical → down, warning → degraded, else up. Solo+ tier gate (status_pages limit).
-
Cron heartbeat monitoring: detecting silent job failures with z-score output analysis
Sonar cron heartbeat: push-first (job pings /sonar/ping/<token>), CronScheduleEvaluator 5-field parser (*, digit, range, step, comma) forward-iterates minute-by-minute to nextExpectedAfter(), isOverdue = now > nextExpected + graceSeconds. missed_ping = WARNING. OutputDiffer: BASELINE_SAMPLE=20, MIN_BASELINE=5, ZSCORE_THRESHOLD=3.0/5.0 (warning/critical), MEDIAN_DROP_FACTOR=0.50/0.01. output_anomaly = WARNING or CRITICAL. Zero content storage — derived metrics only.
-
HTTP monitoring beyond uptime: 4 incident types that catch silent failures
Sonar HTTP probe: 4 incident types — http_down (probe unreachable/timeout), http_status_unexpected (wrong code → WARNING), http_slow (duration > threshold, CRITICAL at 2×, auto-resolves), http_body_mismatch (body_contains substring missing → CRITICAL), schema_drift (SHA256 diff opt-in Pro+, default off). Body cap 1MB, excerpt 512B. FOLLOWLOCATION=false SSRF defence. First probe records baseline silently — no alert.
-
Stripe billing in PHP SaaS: 4 edge cases that bit us in production
Sonar billing: PlanService::PLANS canonical catalog (free/solo $9.99/pro $29/agency $79 + limits enforcement), 4 production fixes — M1 dual-sub guard (redirect to portal), M2 Price ID env rotation fallback (historical DB lookup), M3 event ordering guard (GREATEST last_stripe_event_at), M4 unknown Stripe status preserves access. Trial → Solo limits. invoice.payment_failed = log only, let Stripe dun.
-
Telegram-first monitoring alerts: inline keyboard ack/snooze without a mobile app
Sonar alert pipeline: TelegramAlertSender returns message_id → persisted for editMessageReplyMarkup, SonarCallbackHandler from.id (NOT chat.id) → company_id cross-tenant gate, re-alert cadence (critical=30min/warning=120min/info=never), sonar:ack stamps acknowledged_at (permanent), sonar:snooze:1h stamps snoozed_until (temporary), inline alert flush in RunMonitorChecksJob cuts latency to ~10s.
-
Building an infrastructure monitoring SaaS in PHP: 5 monitor types on one stack
Sonar: 5 monitor types (cron heartbeat + output diff, SSL cert expiry, HTTP uptime/body/schema-drift, domain WHOIS expiry, renewal reminder), Telegram-first with inline ack/snooze, incident digest (template, no AI), 4 tiers (free/Solo $9.99/Pro $29/Agency $79), RunMonitorChecksJob every-minute tick with per-tick budget 50 monitors oldest-checked-first, sonar_tenant_settings 1-to-1 per tenant.
-
Duplicate invoice number handling in production: graceful recovery without data loss
fiskalizacija_invoices UNIQUE KEY uq_company_invoice_number_year (company_id, invoice_number, issue_year GENERATED). generateInvoiceNumber MAX over all types including proformas (prevents proforma gap). PDOException catch on constraint name → 409 + 'invoice may already exist' (double-submit defence, no data loss). issue_year GENERATED ALWAYS AS YEAR(issue_date) STORED — same invoice number legal in different years.
-
AI OCR for invoice drafts in PHP: extracting structured data from PDFs and images
OcrInvoiceDraftTool: VisionAnalyzer 3 input modes (local PDF→document block, local image→image block, remote URL→cURL download→image block), TaskRouter::TASK_VISION, max_tokens=512 temperature=0.0. Extraction prompt: partner, dates, line_items (description/qty/unit_price/vat_rate), totals — Croatian VAT 0/5/13/25, OIB 11 digits, EUR default. parseJsonStrict strips code fences. Draft-only safety: never writes to DB, status=draft, operator fiscalizes manually.
-
PDF invoice generation in PHP: pure binary PDF with embedded DejaVu Sans, no library
Fiskalizacija PDF: two-path architecture — HTML preview (InvoicePdfService, browser print) vs binary PDF download (PdfService pure PHP, DejaVu Sans TTF embedded, A4 595.28×841.89pt, PDF objects directly). QR code via QrCodeService::generateSvg() (pure PHP SVG). HUB-3 payment slip HTML. Fiscalization block: ZKI formatted groups, JIR or 'naknadna dostava pending'. Croatian characters: ć/č/š/ž/đ require Unicode TTF embedding.
-
SOAP in PHP without ext-soap: building the Croatian CIS fiscal connector
CisClient: raw SOAP envelope as PHP string (no ext-soap), 8-step XML-DSig (enveloped, exc-c14n, RSA-SHA1): SHA1 digest of RacunZahtjev → X509Certificate+IssuerSerial → SignedInfo string → PLACEHOLDER Signature inserted → C14N in doc context → openssl_sign → PLACEHOLDER replaced. Client cert via CURLOPT_SSLCERT+SSLKEY (tempnam 0600, cleanup in finally). FINA RDC CA not in Mozilla bundle → custom cacert.pem. SafeXmlLoader LIBXML_NONET+DOCTYPE guard on response.
-
Croatian fiscal invoicing (fiskalizacija) in PHP: SOAP, PKCS12, ZKI, JIR — the complete guide
Fiskalizacija module: Zakon o fiskalizaciji CIS SOAP over HTTPS with XML-DSig (enveloped, exc-c14n, RSA-SHA1, X509Certificate+IssuerSerial), PKCS12 AES-256 encrypted in DB, ZkiGeneratorService (MD5 of concatenated fields), JIR from CIS response, naknadna dostava retry (FiskNaknadnaJob 30min × 10, 48h legal deadline, Telegram alert), 5 AI agents (FiskAgent draft-only), KPD mandatory 2026-01-01, QR code SVG pure PHP.
-
Data tables in PHP without a plugin: Tabulator.js with server-side processing and auto-mode switching
Shinobitables: Tabulator.js wrapper with auto-mode switch (<1000 client, >1000 SSP), single init request (config+data in one POST), ShinobitablesSSP parameterized queries, ShinobitablesFetchTrait controller trait, CSRF request queue with 403 auto-retry, cascading filters, computed columns via sqlexpression alias, ShinobitablesFactory context menu + keyboard shortcuts.
-
Stripe integration in PHP without stripe-php: webhook verification from scratch
StripeBridge: zero-dependency Stripe HTTP client (form-encoded + JSON), Idempotency-Key on all POSTs (tenant_id+sha256(email) for customers, customer_id+price_id for checkouts), HMAC-SHA256 webhook verification with hash_equals + 5-min replay window, StripeException::redact() strips emails + digit runs, TLS pinning CURLOPT_SSL_VERIFYPEER=true.
-
Telegram bots in PHP without a library: webhook-first, inline keyboard, one shared bot
TelegramBridge: webhook-first (no polling), SH-XXXXXX verification code linking, chat-type routing (private=full/group=alert-sink/channel=ignored), TelegramDeliveryJob (queue: alerts, 3 attempts, 30s delay) with sync fallback, TelegramAgentChannel 4096-char chunking, TelegramNotificationBridge push API, HMAC webhook secret validation.
-
NIS2 incident response in PHP: hash-chained timeline, CERT.hr submission, and multi-regulator dossiers
NIS2response: 10 tables, 27 services, hash-chained timeline (SHA256(prev||payload)), weekly tamper-proof root hash to Telegram+email, CERT.hr 3-stage submission with double confirm, 4-regulator dossier (CERT.hr/AZOP/Porezna/HNB), CrossTenantCampaignDetector, STIX 2.1 export, tabletop exercise mode, Art. 23 deadline cascade (24h→72h→1mo).
-
EU AI Act compliance scoring in PHP: per-system Article 9-15 automated evaluation
ComplianceScorer: 10 declarative rule types evaluated against aiact_systems row, articles loaded from aiact-articles.json, weighted average (Art. 11+14=1.5×, Art. 43+47=0.5×), 60s cache with aiact:score: prefix, gap analysis with worst-5-articles, updateSystemScore() auto-triggered from lifecycle write paths.
-
FRIA in PHP: implementing the EU AI Act Fundamental Rights Impact Assessment
AiActFriaWizardController: 6-step FRIA (step 0=DPIA auto-prefill via FriaDpiaBridge, steps 1-6=deployer type/rights/groups/severity/mitigation/monitoring+submit), 12 fundamental rights from EU Charter, 13 affected groups, review_due_date annual cycle, GDPR DPIA cross-link via gdpr_dpia_id, compliance score auto-recomputed on submit.
-
EU AI Act Article 5 runtime safeguards in PHP: blocking prohibited AI practices at the HTTP layer
ProhibitedSafeguardGate: two-tier check (risk_category=prohibited OR runtime_blocked=1), fail-open on missing DB (no DoS of legit traffic), evidence write to aiact_logs_evidence + aiact.prohibited_attempt event + ProhibitedSystemBlocked exception (HTTP 403). AIACT_PROHIBITED_SAFEGUARD_ENABLED env switch. Name lookup tenant-scoped via currentCompanyId().
-
PHP AST scanning with PhpToken: auto-discovering AI systems in your codebase
AiSystemAstScanner: two detection signals (extends AgentDefinition, implements ToolInterface + AI service in ctor), str_contains pre-filter (~100x cheaper than tokenization), PhpToken::tokenize() namespace+use-alias resolution, per-tenant moduli filter, AI_SERVICE_FQNS whitelist with 6 service classes, per-file try/catch.
-
EU AI Act compliance in PHP: a built-in registry with codebase auto-discovery
AIactRegistry: two-tier AI system auto-discovery (hardcoded curated + AST sweep via PhpToken), Art. 4 literacy tracking, Art. 5 runtime prohibited-practices safeguard at HTTP priority 28, Art. 27 FRIA wizard, Art. 71 EU database export, Art. 72 post-market monitoring, Art. 73 serious incident reporting with NIS2 cross-link. No separate compliance SaaS needed.
-
Soft delete in PHP: why it matters for GDPR and how to implement it correctly
Model soft delete: opt-in $softDelete = true adds automatic WHERE deleted_at IS NULL to query(), withTrashed() / onlyTrashed() for admin bypass, trash(deletedBy) vs delete(), GdprRetentionJob atomic transaction (DELETE + auditLogger in one commit), GDPR_RETENTION sentinel, 2-year audit log cleanup.
-
Field-level encryption in PHP: OIB at-rest with AES-256-GCM and key rotation
FieldEncryptor: AES-256-GCM with 12-byte IV + 16-byte auth tag, base64(iv+tag+ciphertext) format, fail-closed encrypt() throws on missing key (ENCRYPTION_FAIL_SILENT escape hatch), legacy plaintext passthrough on decrypt, ENCRYPTION_KEY_PREVIOUS rotation fallback, explicit controller encryption (not ORM-transparent).
-
GDPR compliance in PHP SaaS: manifest-driven audit log, DSAR, and anonymization
GdprManifest auto-scanned from *_gdpr.php files at bootstrap stage 5, GdprRegistry singleton, AuditLogger (logCreate/Update/Delete/View), DsarService cross-manifest search, DataAnonymizer with 6 rules (scramble/fake_email/fake_oib/fake_date/static/null), FieldEncryptor AES-256-GCM for sensitive_fields, gdpr_requests DSAR evidence table.
-
Building a personal AI assistant in PHP: voice notes, semantic memory, Telegram
LIMAlife: 7-phase personal AI (memory/reminders/HTTP → Gmail/Calendar → proactive intelligence → weekly brief → inbox autopilot → SocialScout). AES-256-GCM encrypted memories, ConversationContextEnricher (zero AI calls), EmailClassifier (Groq Llama FREE pre-filter), WeeklyFounderBriefJob (text+voice OGG), split per-source SocialScout jobs (HN/Reddit/X), ShinobiRecallClient grounding.
-
Multi-provider AI chat in PHP: tiered routing saves 80% of tokens
LIMAi: BYOK provider model (Anthropic/OpenAI/Groq/Gemini/Ollama), two-tier routing (Tier 1 keyword pre-routing zero tokens + Tier 2 KIK orchestrator for ambiguous), directChat fallback to TaskRouter::TASK_DRAFTS (Gemini Flash FREE), AITokenTracker unified tracking, ConversationModel per-user history, SSE streaming chat.
-
Running LLMs locally with Ollama in PHP: zero API cost for classification and embeddings
Ollama integration: OLLAMA_BASE_URL env var → OpenAIAdapter (same code path as OpenAI/Groq), isConfigured() checks base_url not api_key, api_key is ceremonial ('ollama' string), default model qwen2.5:14b. Embeddings via /api/embeddings (native) not /v1/embeddings. Transcription via whisper.cpp. LAN host setup. OLLAMA_BASE_URL is operator-configured — no SSRF guard needed.
-
Circuit breaker for AI providers in PHP: OPEN/HALF_OPEN/CLOSED state machine
CircuitBreaker: CLOSED/OPEN/HALF_OPEN state machine, failureThreshold=3, transientRecoverySeconds=300 (5min), permanentRecoverySeconds=1800 (30min), DB-backed ai_provider_health (one indexed PK read/request). ProviderError: 6 categories — PERMANENT_BILLING vs RATE_LIMITED distinction (413 is TPM cap not billing, URL-stripped match, billing before 4xx/401 check). Retry-After honored. upsert avoids deprecated ON DUPLICATE KEY UPDATE.
-
Per-tenant AI usage tracking in PHP: attributing every LLM token to its tenant
Two tracking systems: ai_usage_daily (day-level aggregates for budget monitoring, composite PK on date+tenant+provider+model) and limai_token_usage (per-call rows with execution_id for agent log correlation). tenant_id is the required first parameter in every write path — silent attribution bugs aren't possible.
-
Multi-provider AI with automatic failover: how TaskRouter works in PHP
TaskRouter: 10 named task roles, failover chains (paid → FREE on failure), a stateful circuit breaker in ai_provider_health, 6 provider adapters, and zero vendor lock-in in application code. Every AI call is one method; the router handles the rest.
-
CI performance gating in PHP: blocking PRs that regress p95 latency
KikaGitContext: 7-char commit hash + branch from GitRunner (per-instance memoized), 16-hex env hash (PHP_VERSION|opcache|jit|memory_limit|os) for baseline filtering across PHP upgrades. AssertionEvaluator: Blackfire-style grammar (metric.path OP value[unit]), units us/ms/s/B/KB/MB/%, unknown path fails loud. GitHub commit status reporting.
-
PHP memory leak detection: Theil-Sen slope on synthetic workload iterations
MemoryLeakDetector: 20-iteration warmup before baseline (JIT/opcache excluded), 200-point even-spaced subsample for Mann-Kendall O(n²) cost control, Theil-Sen slope as the robust estimator, stride-corrected bytes-per-iteration, leak=slope>0 AND p<0.05. Synthetic workload: container resolve + Config::get + Request/Response cycle + gc_collect_cycles().
-
Why % delta on mean is broken: Mann-Kendall, Cohen's d, and Theil-Sen for PHP benchmarking
Standard 'percentage change from baseline mean' misses real regressions and fires false alarms. KIKAbenchmarking implements four proper statistical methods: Mann-Kendall trend test (rank-based, no normality assumption), Theil-Sen slope (outlier-robust), Cohen's d effect size (is this change meaningful?), and a pure-PHP erfc for p-values.
-
Proof-of-Work CAPTCHA in PHP: blocking bots without Google reCAPTCHA
PoWChallengeService: SHA-256 leading-zero-bits puzzle, 18-bit difficulty (~1s modern CPU), server-side HMAC integrity + 5-minute TTL, IP-bound 1-hour verified cookie. No reCAPTCHA, no hCaptcha, no Turnstile, no external API call. The cookie format: {ip}|{issued_at}|{hmac}, timing-safe verification.
-
Attack chain reconstruction in PHP: forensic timeline for NIS2 early-warning
AttackChainReconstructor: 5 phases (recon/probe/exploit/exfiltration/benign), EXPLOIT_SCORE_THRESHOLD=75, SENSITIVE_PATH_PATTERN for exfiltration, 4 data sources merged chronologically with ±2s dedup, exfiltration heuristic score (suspect_routes*20 + min(40,bytes/100k)), NIS2 Art. 23(4) 24h early-warning forensic export.
-
Self-tuning WAF rules in PHP: automatic false-positive decay without disabling rules
RuleTuningService: weekly FP-rate analysis via blocked-then-manually-unblocked signal, FP_RATE_THRESHOLD=0.5, MIN_SAMPLE_SIZE=10, DECAY_AMOUNT=10, FLOOR_SCORE=25. Stale rules (0 hits in REVIEW_DAYS=30) flagged for admin review — never auto-disabled. Atomic applyTuning() in DB transaction with security_borna_rules_history audit trail. revertRule() restores original_score.
-
Behavioral baseline security in PHP: detecting anomalies without rule signatures
BehaviorBaselineComparator: per-(IP, tenant) hourly baseline over 168 hours, Cohen's d on 5 dimensions (request_count, endpoint_entropy, status_2xx/4xx/5xx rate), directional gating (request_count only flags upward spikes), confidence from sample count, minimum 14 samples. Same Cohen's d engine as KIKA and LUKA.
-
Building a WAF in PHP: per-tenant attack attribution that Cloudflare doesn't do
BORNAsecurity: a PHP WAF that knows which tenant is being attacked. FCrDNS-verified crawler bypass, 5σ behavioral anomaly detection, attack chain reconstruction across tenants, self-tuning rules via operator feedback, and a PoW CAPTCHA that requires no Google. No Cloudflare subscription needed.
-
Statistical query regression detection in PHP: Cohen's d on MySQL timing baselines
QueryBaselineComparator: MIN_BASELINE_SAMPLES=14, 7-day hourly median baseline from monitoring_luka_query_baselines, Cohen's d reused from KIKA TrendAnalyzer (single source of truth), directional gate (positive d only = regression), NULL-safe tenant_id <=> operator, confidence tiers (high≥100/medium≥24/low<24 samples).
-
Cross-source incident correlation in PHP: when one event is four signals in disguise
IncidentCorrelator: 4 declarative patterns (ddos_via_expensive_query/breach_with_service_degradation/systemic_failure/user_experience_degradation), every-5-minute cron scan, 4 data sources loaded per-window, per-tenant grouping, idempotent insert on (signature+window_start), luka.correlated_incident event dispatch.
-
APM in PHP without a SaaS vendor: endpoint profiling from the middleware layer
LUKAmonitoring captures every request's query count, timing, and memory from a priority-5 middleware. p50/p95/p99 per route, N+1 detection, Cohen's d query regression, and a cross-addon incident correlator that spots DDoS-via-expensive-query and breach-with-service-degradation. No Datadog subscription.
-
The dedup blind spot: when an AI fix introduces a new bug on the same route
Self-Healing dedup blind spot: dedup_key = sha1(source|event_type|route|endpoint|rule_id|anomaly_type|normalised_message_hash), DEFAULT_DEDUP_WINDOW_MINUTES=60, MUTING_STATUSES = OPEN+IGNORED. New bug in dedup window with same normalised message → collapses into original incident → no new Telegram, no new PR. v2 message hash (2026-06-19) mitigates different-error case. 5-min health check window is the detection path.
-
Setting up Self-Healing PHP on a shared host: git, GitHub, Telegram, cron in 30 minutes
Self-X setup: git init on live (tracks origin/main), GitHub PAT (repo scope), /selfheal/webhook + SELFHEAL_GITHUB_WEBHOOK_SECRET, claude.ai Routine 'Self-Healing auto-PR', cron worker queue:selfheal (out-of-process deploy), SELFHEAL_HEALTH_URL, 7 protected prod files backed up around git reset --hard. Two deploy workflows: A (operator push ~0.6s) + B (AI PR merge + snapshot + 5min health check).
-
Self-Optimizing PHP: catching P95 regression before it breaches your budget
APM tools show you a P95 regression dashboard. Self-Optimizing opens a GitHub PR to fix it. Mann-Kendall trend test + Cohen's d magnitude gate filter noise. The same 4-tap operator flow as Self-Healing — but for performance regressions, not broken code.
-
Self-Explaining PHP: AI triage before you open the log
Every production ERROR triggers a 3-bullet AI summary in Telegram: what happened, why probably, and exactly which file:line to look at first. The analysis arrives before you've opened the log. Cost: ~$0.0001. Latency: 30-60 seconds. No Sentry needed.
-
Self-Healing PHP: AI fixes production bugs in 4 phone taps
A production bug fires. Telegram pings my phone. I tap Analyze. Claude reads the repo and opens a PR. I review on my phone and tap Merge. The system deploys, verifies, and closes the incident. Total operator time: 30 seconds. On a $5/month shared host.
-
Sensitive data masking in PHP logs: OIB, IBAN, credit card, email auto-redacted
Shinobi Apps framework Logger: maskSensitiveData() applied once to context before any handler receives it. Two-pass: (1) key-based — SENSITIVE_KEYS list (password/token/secret/api_key/credit_card/ssn/pin/cvv/authorization) → '***MASKED***'. (2) value-based — regex patterns: credit card (13-19 digit groups → ****-****-****-last4), JWT (eyJ.*.* → prefix***JWT_MASKED***), Bearer token (Bearer .{20,} → prefix***MASKED***), hex hash (32+ hex chars → first8***MASKED***). Control-char sanitization on log message string.
-
PHP logging severity as a routing decision: the 3-question framework
With Self-Healing and Self-Explaining in production, every log call has a cost: CRITICAL fires an AI auto-PR pipeline, ERROR fires an AI triage call, WARNING costs nothing but noise. A 3-question decision tree that makes severity selection mechanical rather than stylistic.
-
PHP input validation with 18+ built-in rules: OIB, phone, decimal and more
Shinobi Apps framework Validator: pipe-separated rule string 'required|oib|max:11' or array form. OIB: 11-digit regex + Luhn-variant checksum (mod 10+11 ISO 7064 MOD 11-2). PATTERNS const for alpha_spaces/alpha_num/phone/decimal/currency/time_24h/oib/plain_text/comment. Conditional-required gates: required_if, required_unless, required_with, required_without. Unknown rule → throw InvalidArgumentException (fail-loud). Dot-notation for nested arrays. Stop on first failure per field.
-
PHP event dispatcher: priority queues and wildcard listeners
Shinobi Apps framework EventDispatcher: addListener with priority (higher = earlier). addWildcardListener('borna.*') matches any event with that prefix. getSortedListeners merges exact + wildcard entries, usort by priority, caches result per event name. Listener exceptions: WARNING-level log + continue in production, re-throw in development. isPropagationStopped() allows listener chain short-circuit. EventDispatcher::emit in QueueManager catches listener failures (broken subscriber never sinks job execution).
-
Dependency injection in PHP without a package: reflection autowiring from scratch
Shinobi Apps framework Container: singleton vs request scope, reflection-based constructor parameter resolution, APCu L2 cache for constructor signatures (namespace keyed by Container.php mtime, TTL 3600s). Circular dependency detection via $resolving stack. Lazy EventDispatcher resolution from container (bootstraps where DI registers after QueueManager). register/singleton/request/get/has API. Auto-class resolution for unregistered class names.
-
PHP template engine without Twig: production caching and @directive preprocessing
Shinobi Apps framework template engine: DirectiveProcessor processes @csrf/@include/@asset before template execution. @csrf returns PHP code (not static HTML) — nonce evaluated at runtime, never baked into cache file. processExpressions {{ $x }} → htmlspecialchars runtime echo, {!! $x !!} → raw (unescaped) — prior bug: inlined value into cache = stored RCE via {!! SVG }}. Cache keyed by source path hash, not request vars. CSP nonce via Request::getCurrent()->getNonce().
-
PHP cron scheduler: self-hosted, zero dependencies, per-minute resolution
Shinobi Apps framework Scheduler: queue_scheduled_tasks table, registerIfNeeded (file cache → DB upsert, hash of jobClass+expression+jobData), ONCE marker for one-time tasks, runDue optimistic atomic claim (UPDATE WHERE old next_run_at → affected_rows=1 wins, prevents duplicate dispatch), INSERT ON DUPLICATE KEY UPDATE with is_active omitted (preserves user toggle). Scheduler::ONCE for delayed post-deploy tasks. Expression: cron 5-field or dailyAt HH:MM.
-
PHP job queue on a shared host: no Redis, no RabbitMQ, just MySQL and cron
Shinobi Apps framework queue: DatabaseDriver (MySQL-backed, no Redis). QueueManager priority queue list (default, emails, alerts, webhooks, ai-analysis, maintenance, notifications) + auto-discovery of unknown queues from storage (new addon queue Just Works). processMany round-robin, processManyUntil(deadline) for time-bounded critical-path drain. Exponential backoff (60s × 2^attempts). Dynamic class whitelist for unserialize (PHP Object Injection defence). Queue lifecycle events via EventDispatcher.
-
PHP query builder: building type-safe SQL without an ORM
Shinobi Apps framework QueryBuilder: fluent interface over PDO, all params bound automatically (zero interpolation). ALLOWED_OPERATORS allowlist for where/orWhere/having. validateQualifiedColumnName regex for orderBy/groupBy (prevents backtick injection). whereIn empty array → 1=0 sentinel (never returns all rows). select() trusted-caller design (no user input). aggregate helpers (sum/avg/max/min) validate column before SQL fragment.
-
Active Record in PHP without an ORM: how the Shinobi Apps framework's Model works
An Active Record implementation with QueryBuilder, typed attribute casts, soft delete, eager loading with whereIn batching, and model lifecycle events — without Doctrine, Eloquent, or any Composer package. What zero-dependency means for the database layer.
-
PHP migration system: forward-only, one file per change, shared-host compatible
SQL-only migrations, no PHP interface. Forward-only with no down() method. One logical change per file. Checksum verification on re-run. Shared-host compatible: no information_schema access needed, MySQL 5.5+ syntax only. Works across multiple databases in one command.
-
2FA and magic links in PHP: TOTP and passwordless login without packages
Pure-PHP RFC 6238 TOTP: HMAC-SHA1 with dynamic truncation, base32 encode/decode, ±30-second drift window. Magic link login: 32-byte random token, 15-minute TTL, hash stored, raw in URL. Neither requires a Composer package.
-
PHP session security: database-backed sessions, salted fingerprinting, and deferred writes
Database-backed sessions only (file driver removed). Salted SHA-256 fingerprint that an attacker can't reproduce without server-side salt. Deferred write: session lock released immediately after start(), in-memory delta flushed at end of request. flock-based regeneration lock for parallel requests.
-
Rate limiting in PHP: two-lane defense against DDoS and brute force
One rate limiter, two lanes per protected route. Lane 1 counts every POST per IP (anti-DDoS, high threshold). Lane 2 counts only failed auth attempts per email (anti-brute-force, 5 tries). Sliding window with weighted previous window. BORNA enrichment via events.
-
Content Security Policy in PHP: the nonce approach that actually works
A strict CSP with per-request nonces, no 'unsafe-inline', and no X-XSS-Protection (which causes more bugs than it prevents). How we handle dynamic styling in a CSP-compliant way: CSS custom properties via setProperty() instead of inline style attributes.
-
CSRF protection in PHP without a framework: rotating tokens, grace periods, and the @csrf directive
How the Shinobi Apps framework implements CSRF protection: bin2hex(random_bytes(32)) tokens stored in session, 30-minute rotation with a 10-minute grace period for tabs left open, hash_equals() for timing-safe comparison, and an @csrf directive that outputs window.CSRF_TOKEN instead of a meta tag.
-
One PHP codebase, three MySQL servers: per-domain database routing without code changes
How to route a single PHP codebase to different MySQL databases based on HTTP_HOST — without code changes in any model or controller. The full implementation: ConnectionRouter, strict host validation, TLS to remote DBs, and CLI --connection flag.
-
Trial lifecycle in PHP SaaS: from signup to suspended in three database columns
A 14-day trial managed by three DB columns (plan_status, trial_ends_at, is_public_signup), a daily cron job that flips expired trials to suspended, and middleware that redirects suspended users to the upgrade page. No billing framework required.
-
Domain-driven tenant onboarding: how email domain matching beats invite codes
When a new user signs up with an @company.hr email, they automatically join their company's existing tenant instead of creating a new one. No invite code, no admin action required. How to build email domain matching in PHP with a free-domain blocklist and JSON_CONTAINS.
-
Multi-tenant SaaS in PHP without a multi-tenant framework
Row-level tenancy in PHP using one database, one codebase, and a korisnici_companies table. How currentTenantId() and allowed_modules replaced per-tenant databases and per-tenant codebases — and the two contexts that can never be mixed up.
-
Addons vs modules: the architectural boundary that makes a 60k-line PHP SaaS manageable
How one PHP codebase serves infrastructure monitoring, fiscal invoicing, accounting, and a personal AI assistant without coupling any of them. The addons-vs-modules boundary — what it is, why it matters, and the decision tree I use to decide where new code goes.
-
Lazy vs eager bootstrap in PHP: the production incident that taught me the hard way
Three bootstrap patterns for PHP service registration — pure eager, pure lazy, and the split approach. Why lazy sounds smart, why it breaks cross-cutting hooks, and what the 2026-04-28 incident looked like at 11pm.
-
Inside a PHP framework: 20 subsystems, a 5-stage bootstrap, and a request lifecycle you can read in one sitting
What happens between a browser request hitting Apache and your controller method running? Walk through the Shinobi Apps framework architecture: 5-stage bootstrap, 8-layer middleware pipeline, 20 core subsystems, and a request lifecycle that fits in your head.
-
The custom PHP autoloader: a 4-prefix lookup table and one is_file() call
A complete PSR-4-compatible autoloader in 50 lines. Four namespace prefixes, one is_file() check per class load, and OPcache doing the actual caching. No class-map generation step, no Composer runtime, no regex. Here's exactly how it works.
-
Why I built a zero-dependency PHP framework in 2025
Composer is the gold standard. Symfony and Laravel are mature. So why ship a custom PHP 8.3 framework with zero composer dependencies in 2025? The honest answer — and what it actually cost me.