惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
Security Latest
Security Latest
P
Proofpoint News Feed
GbyAI
GbyAI
PCI Perspectives
PCI Perspectives
博客园 - Franky
N
Netflix TechBlog - Medium
博客园_首页
WordPress大学
WordPress大学
K
Kaspersky official blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Vercel News
Vercel News
T
Threatpost
The Hacker News
The Hacker News
H
Help Net Security
S
Securelist
Recent Announcements
Recent Announcements
腾讯CDC
T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Engineering at Meta
Engineering at Meta
C
Cisco Blogs
V
V2EX
C
Check Point Blog
S
Schneier on Security
Cyberwarzone
Cyberwarzone
C
Cybersecurity and Infrastructure Security Agency CISA
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog RSS Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Jina AI
Jina AI
M
MIT News - Artificial intelligence
T
Threat Research - Cisco Blogs
博客园 - 叶小钗
A
Arctic Wolf
AWS News Blog
AWS News Blog
Latest news
Latest news
Martin Fowler
Martin Fowler
Recorded Future
Recorded Future
Last Week in AI
Last Week in AI
The GitHub Blog
The GitHub Blog
小众软件
小众软件
B
Blog
aimingoo的专栏
aimingoo的专栏
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
P
Palo Alto Networks Blog
Spread Privacy
Spread Privacy

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything BFF模式详解:构建前后端协同的中间层 I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Why `mixed` Is the Worst Type in Your PHP Codebase (and How to Kill It)
Gabriel Anha · 2026-05-24 · via DEV Community

A team I talked to last month had 1,400 mixed return types across their Laravel 11 codebase. PHPStan level 6 was green. Tests passed. A junior dev refactored one helper, and three controllers started returning HTTP 500s in staging. Nothing flagged it. Nothing could.

mixed is the PHP type system saying "I give up." Laravel's own docs sprinkle it everywhere. PHPStan tolerates it through level 7. Your codebase quietly accumulates it. Every mixed is a load-bearing crack you can't see until something downstream snaps.

Five concrete failure modes, then a 50-line script that finds your worst offenders.

What mixed actually means (and why "anything" is the problem)

mixed was added in PHP 8.0 as the explicit version of "no type." It accepts int, string, array, object, null, false, closures, resources. Everything PHP can hold. It's the top type of the language.

Here's the trap: a top type tells you nothing. If a function returns mixed, the caller has to assume the worst case for every branch. Every comparison. Every method call. The compiler (in PHP's case, the static analyser) has no information to work with.

The pre-8.0 alternative was a missing return type, which static tools treated the same way. PHP 8.0 didn't introduce a new problem. It gave the existing problem a name. The name didn't help. It made the problem easier to write down and harder to flag as a code smell.

Failure 1: IDE autocomplete dies on every mixed return

You write $order = $repo->find($id); and hit ->. PHPStorm gives you nothing. Or worse, it gives you every method on every class in your project, sorted alphabetically. You scroll past __construct, accept, acknowledge, actAs...

// Repository.php: the kind of code that ages badly
final class OrderRepository
{
    public function find(int $id): mixed  // <-- the crime
    {
        $row = DB::table('orders')->find($id);
        if (!$row) {
            return null;
        }
        return Order::fromRow($row);
    }
}

Enter fullscreen mode Exit fullscreen mode

The signature says "could be anything." So PHPStorm assumes it is. You lose go-to-definition. You lose rename refactors on Order fields. You lose the warning that says "you're calling ->customerId on a null." You're typing PHP 5.6 in 2026.

The fix is mechanical:

public function find(int $id): ?Order
{
    $row = DB::table('orders')->find($id);
    return $row ? Order::fromRow($row) : null;
}

Enter fullscreen mode Exit fullscreen mode

One word. The IDE wakes up. Rename refactors land everywhere they should. The next dev who reads find() knows what comes back without grepping the body.

Failure 2: PHPStan level 6+ can't catch null deref on mixed

This is the failure mode that bites in production. PHPStan can prove a lot about your code, but mixed is a wall.

public function totalForCustomer(int $customerId): float
{
    $orders = $this->cache->get("orders.$customerId"); // returns mixed
    $sum = 0.0;
    foreach ($orders as $order) {
        $sum += $order->total;
    }
    return $sum;
}

Enter fullscreen mode Exit fullscreen mode

Run PHPStan level 7 on this. It passes. The foreach on mixed, the ->total access on mixed. PHPStan can't reason about either because it has no upper bound. The runtime catches it: Cannot access property total on mixed, but only when the cache misses, which is what you don't catch in tests.

Level 8 is where PHPStan stops being kind. At level 8, calling a method on mixed is a violation. Iterating mixed is a violation. mixed[] access is a violation. The fix is to type the cache wrapper itself:

final class OrderCache
{
    /** @return list<Order> */
    public function getOrders(int $customerId): array
    {
        $raw = $this->store->get("orders.$customerId");
        if (!is_array($raw)) {
            return [];
        }
        return array_map(fn($r) => Order::fromArray($r), $raw);
    }
}

Enter fullscreen mode Exit fullscreen mode

The PHPDoc generic and the runtime check at the boundary do the work. Inside the rest of the codebase, $cache->getOrders($id) is a list<Order>. No mixed. No null deref. PHPStan level 8 stays green.

Failure 3: Generic wrappers (Collection<mixed>) hide nothing

Laravel's Collection is the most-used class in any Laravel codebase. It's also the most lied-to. The default type when you don't add a PHPDoc is Collection<int, mixed>:

public function activeOrders(): Collection
{
    return Order::where('status', 'active')->get();
}

Enter fullscreen mode Exit fullscreen mode

PHPStan sees this as Illuminate\Database\Eloquent\Collection<int, Model> at best, Collection<mixed> if you're using base Collection. The chained calls below all run on mixed:

$activeOrders
    ->filter(fn ($o) => $o->customerId === $id)  // mixed->customerId
    ->map(fn ($o) => $o->total)                  // mixed->total
    ->sum();

Enter fullscreen mode Exit fullscreen mode

Every arrow is a guess. Every refactor (renaming customerId to customer_id, adding a ? to total) silently misses these call sites.

The fix is the PHPDoc generic:

/** @return Collection<int, Order> */
public function activeOrders(): Collection
{
    return Order::where('status', 'active')->get();
}

Enter fullscreen mode Exit fullscreen mode

PHPStan and PHPStorm both honour that annotation. The ->filter callback now gets a typed Order. The ->map returns Collection<int, float>. The ->sum is typed float. Type information flows through the pipeline.

larastan/larastan enables this for Eloquent collections out of the box on level 6+. The catch: you have to write the generic. The default (a Collection with no annotation) is Collection<mixed>. That's where most codebases live.

Failure 4: Refactors break in three places downstream

A small rename illustrates the compounding cost. You have a getConfig() helper returning mixed:

function getConfig(string $key): mixed
{
    return config($key);
}

// Three callers, all using it differently:
$ttl = getConfig('cache.default.ttl');              // expects int
$drivers = getConfig('queue.connections');          // expects array
$timeout = getConfig('http.timeout');               // expects ?int

Enter fullscreen mode Exit fullscreen mode

You decide getConfig is silly (since config() already exists) and delete the helper. The IDE's rename refactor doesn't know any of the call sites are special, because they all consumed mixed. You delete the helper, the call sites fall back to config() directly, and three of them now use the value differently than they should.

Worse: you decide to add validation. getConfig should throw on missing keys:

function getConfig(string $key): mixed
{
    $value = config($key);
    if ($value === null) {
        throw new ConfigMissing($key);
    }
    return $value;
}

Enter fullscreen mode Exit fullscreen mode

Now everywhere that consumed ?int from this function silently changed contract. PHPStan can't help, because mixed accepts both int and ?int. Tests pass. Production throws on first cache-miss after deploy.

The fix here isn't generics. It's: small, single-purpose typed helpers.

final class CacheConfig
{
    public function ttl(string $store): int
    {
        $value = config("cache.stores.$store.ttl");
        if (!is_int($value)) {
            throw new ConfigMissing("cache.stores.$store.ttl");
        }
        return $value;
    }
}

Enter fullscreen mode Exit fullscreen mode

You can't refactor a typed contract without breaking the type system. That's the whole point of types.

Failure 5: mixed in trait method signatures forces every consumer to widen

This one is subtle. A trait method with a mixed return signature poisons every class that uses it:

trait HasMetadata
{
    public function getMetadata(string $key): mixed
    {
        return $this->metadata[$key] ?? null;
    }
}

final class Order
{
    use HasMetadata;

    public function shippingAddress(): Address
    {
        $raw = $this->getMetadata('shipping');  // mixed
        return Address::fromArray($raw);        // PHPStan: ok, mixed accepts array
    }
}

Enter fullscreen mode Exit fullscreen mode

PHPStan level 8 flags Address::fromArray($raw) because $raw is mixed and fromArray expects array. To silence it, the dev adds a runtime cast: assert(is_array($raw)). That works, but it's a runtime tax for a type system failure.

The real fix is to remove mixed from the trait by making the trait generic via PHPDoc:

/**
 * @template TValue
 */
trait HasMetadata
{
    /** @var array<string, TValue> */
    private array $metadata = [];

    /** @return TValue|null */
    public function getMetadata(string $key)
    {
        return $this->metadata[$key] ?? null;
    }
}

final class Order
{
    /** @use HasMetadata<string|array<string, string>> */
    use HasMetadata;
}

Enter fullscreen mode Exit fullscreen mode

PHPStan honours @template on traits. The consumer pins the type. The mixed is gone from the call sites without runtime asserts.

Traits are where mixed accumulates fastest, because they're framework-y and "reused." Every reuse propagates the weakest signature.

The replacement ladder: mixed to union to interface to concrete type

When you find mixed in your code, climb this ladder:

  1. Concrete type: if you can write Order, write Order. Never settle for less.
  2. Nullable concrete: ?Order if the method can legitimately return nothing.
  3. Union: Order|Refund|null when the function returns one of a few things. Discriminated unions are PHP's way of saying "one of these."
  4. Interface: Refundable if you care about behaviour, not class identity.
  5. PHPDoc generic: list<Order>, array<string, Money>, Collection<int, Order>. PHPStan understands these.
  6. mixed: only at trust boundaries (deserialising JSON, reading from $_POST, hitting a cache before validation). And then immediately narrow, before passing the value anywhere else.

Rule of thumb: mixed should live in your codebase for one line. The line after it should narrow.

A 50-line audit script that finds your worst mixed offenders

You don't need PHP-Parser for the first pass. Grep with the right pattern gets you 90% of the way there. Save this as bin/audit-mixed.sh:

#!/usr/bin/env bash
# audit-mixed.sh: rank files by mixed-density
set -euo pipefail

ROOT="${1:-src}"
TMP=$(mktemp)

# count mixed occurrences per file, ignoring vendor/tests
find "$ROOT" -name '*.php' \
    -not -path '*/vendor/*' \
    -not -path '*/tests/*' \
    -print0 \
  | while IFS= read -r -d '' file; do
      # match `: mixed` returns, `mixed $var` params, `@param mixed`,
      # `@return mixed`, and `@var mixed` PHPDoc tags
      count=$(grep -cE '(\:\s*mixed\b|mixed\s+\$|@(param|return|var)\s+mixed)' "$file" || true)
      lines=$(wc -l < "$file")
      if [ "$count" -gt 0 ]; then
          # density = mixed count per 100 lines
          density=$(awk "BEGIN { printf \"%.2f\", ($count * 100) / $lines }")
          printf '%s\t%d\t%d\t%s\n' "$density" "$count" "$lines" "$file" >> "$TMP"
      fi
  done

echo "DENSITY  COUNT  LINES  FILE"
echo "-----------------------------"
sort -rn "$TMP" | head -30
rm "$TMP"

Enter fullscreen mode Exit fullscreen mode

Run it: ./bin/audit-mixed.sh src. You get the 30 worst offenders sorted by mixed-density-per-100-lines. Density matters more than raw count. A 2000-line model with 8 mixed is healthier than a 50-line trait with 6.

For the PHP-Parser version (more accurate, catches dynamic property access and ignores comments), nikic/php-parser 5.x plus a NodeVisitorAbstract that counts Identifier nodes named mixed inside Stmt\ClassMethod and Stmt\Function_. The bash version is what you want for a CI check. Add a line that fails the build if the top file's density crosses a threshold you commit to (start at 3.0, ratchet down monthly).

PHPStan level 8 is the enforcement

The audit tells you where you stand. PHPStan level 8 keeps you there.

In phpstan.neon:

parameters:
    level: 8
    paths:
        - src
    ignoreErrors: []
    treatPhpDocTypesAsCertain: true
    checkMissingIterableValueType: true
    checkGenericClassInNonGenericObjectType: true

Enter fullscreen mode Exit fullscreen mode

Level 8 forbids:

  • Method calls on mixed
  • Property access on mixed
  • Array access on mixed
  • Foreach over mixed
  • Returning mixed from a function whose declared return is more specific

It allows mixed itself as a declared type (PHP allows it, PHPStan won't fight the language). But it forces you to narrow before use. Combined with the audit script, you get steady forward progress: PHPStan stops new mixed from being added in unsafe ways; the audit pressures the team to delete the old ones.

The team I mentioned at the top moved 1,400 mixed returns to 280 over a quarter. Their HTTP 500 rate from type errors dropped to near-zero. The PHPStan baseline file shrunk every week. Nobody wrote a single line of new validation code. They just typed what was already there.

mixed is the easiest type to write. It's the most expensive to keep.

What's the worst mixed you've ever inherited? Drop the density score from audit-mixed.sh in the comments.


If this was useful

The mixed problem is a symptom: framework defaults that lean on dynamic typing leak into the domain code where they don't belong. The fix is a clean boundary between the framework layer and the typed core. Decoupled PHP is the architectural layer your codebase reaches for after it outgrows the framework defaults: repository interfaces, value objects, use cases that never see a mixed.

Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework

Available on Kindle, Paperback, and Hardcover. English, German, and Japanese editions out now — Portuguese and Spanish coming soon.