今日已更新 67 条资讯 | 累计 29520 条内容
关于我们

标签:#p

找到 12217 篇相关文章

AI 资讯

Your Laravel Models Aren’t the Problem. Hidden Workflows Are.

Most Laravel applications do not become difficult to maintain because somebody made one obviously terrible architectural decision. They get there through dozens of small decisions that looked completely reasonable at the time. A controller grows beyond a comfortable size, so part of its logic moves into an Eloquent model. Later, the application needs to send a notification after an order ships. Then inventory must be checked through an external API. Accounting requests an ERP integration, and marketing wants loyalty points awarded after dispatch. Each change adds only a few lines. Since the Order model is already available wherever the feature is being implemented, adding one more method feels natural: $order -> ship (); It is concise, expressive, and pleasantly object-oriented. Six months later, however, that innocent method may be updating several tables, calling two APIs, dispatching events, sending notifications, and deciding whether the entire operation is allowed. The model has quietly become the place where the application runs its business workflows. That is the real problem. It is not that the model is “fat.” It is that persistence, domain decisions, and application orchestration have been mixed together until nobody can change one without understanding all three. Business Logic in Eloquent Models Is Not Automatically Wrong The common advice to remove all business logic from Laravel models goes too far. Eloquent follows the Active Record pattern. Martin Fowler describes Active Record as an object that represents a database row, encapsulates database access, and adds domain logic related to that data. In other words, an object containing both state and behavior is not an architectural mistake by itself. A model should be allowed to answer questions about itself: class Order extends Model { protected function casts (): array { return [ 'paid_at' => 'datetime' , 'expires_at' => 'datetime' , ]; } public function isPaid (): bool { return $this -> paid_at !== nul

2026-08-04 原文 →
AI 资讯

I built an invoice generator with no backend — the whole app is one HTML file

Every invoicing tool I tried wanted an account, a subscription, and a copy of my client list on its servers — then charged me monthly to put my own logo on my own invoice. So I built the opposite. Billfold is a complete invoice generator that runs entirely in your browser. No account, no backend, no build step. The whole app is a single index.html file you could email to yourself. It's MIT-licensed and the source is right here: github.com/quantum-hacker0/billfold . Here are the three parts that were actually fun to build. 1. "No server" isn't a privacy policy — it's the architecture The usual pitch is "we take your privacy seriously." That's a promise you have to trust. I wanted it to be a fact you can verify : Open DevTools → Network, create an invoice, and count the requests. It's zero. There's nothing to upload because there's nowhere to upload it. Data lives in localStorage . The app is HTML/CSS/JS inlined into one file — no framework, no bundler, no node_modules . Download it once and it works offline forever. 2. Sharing an invoice without a database — put it in the URL hash This was the interesting constraint. How do you send someone a view-only invoice when you have no server to store it on? The trick: encode the whole document into the URL hash fragment . The fragment (everything after # ) is the one part of a URL that browsers never send to the server — it stays client-side. function shareLink ( state ) { const json = JSON . stringify ( state ); const encoded = btoa ( unescape ( encodeURIComponent ( json ))) . replace ( / \+ /g , ' - ' ). replace ( / \/ /g , ' _ ' ). replace ( /=+$/ , '' ); // base64url return location . origin + location . pathname + ' #v= ' + encoded ; } The recipient's browser reads the fragment, decodes it, and renders the invoice locally. The data rides inside the link and never touches a host — not even mine. PDF export, by the way, is just window.print() with a print stylesheet. 3. Invoices as URLs — with an npm package Because the a

2026-08-04 原文 →
AI 资讯

Your MCP tool takes three minutes. Now what?

I maintain an MCP server that generates music. One call takes anywhere from 40 seconds to three minutes, because there is a model rendering audio on the other end. That does not fit the shape MCP tools are usually written in: call it, get an answer, move on. Everything about the transport assumes the answer is close by. It is worth writing down what actually breaks when it isn't, because "my tool is slow" turns out to be three separate problems wearing one coat. What breaks The obvious first version is a single tool that kicks off the job and awaits the result. server . registerTool ( ' generate_music ' , { /* ... */ }, async ( args ) => { const task = await lacuna . music . generations . create ( args ) const done = await waitUntilReady ( task . id ) // three minutes later return { content : [{ type : ' text ' , text : JSON . stringify ( done ) }] } }) 1. You do not own the timeout. The MCP client does. Claude Desktop, Claude Code, Cursor and the rest each pick their own tool-call deadline, and none of them ask you what yours is. A tool that usually returns in 90 seconds and occasionally takes 200 will work on your machine and fail on someone else's, which is the worst possible failure distribution to debug. 2. If you hand the polling to the model, the model quits. The obvious fix is to return a pending task immediately and expose a get_generation tool so the agent can check on it. The agent will check on it. Twice. Maybe three times. Then it decides the job is wedged and tells the user "this seems to be taking a while, would you like me to keep checking?" — which is a reasonable thing for a helpful assistant to say and a terrible thing for a job that had 40 seconds left. You have converted a slow tool into an unreliable one. 3. Polling burns the context window. Every poll puts a full task object back in the transcript. Twenty polls of a JSON blob is real budget, spent entirely on the word pending . Three tools instead of one What ended up working is splitting the

2026-08-04 原文 →
AI 资讯

I gave Claude read access to my Google marketing stack. Now I just ask it questions.

Opening Google Analytics to answer one question is a special kind of tax. You know the number is in there. You also know it's four clicks, two date pickers and a dimension dropdown away, and by the time you've found it you've forgotten what you wanted it for. So I built Metrifyr : a remote MCP server that puts my Google marketing stack behind my AI agent. Nothing to install: connect it once (Claude, Cursor, VS Code, any MCP client), then ask the question in plain language and it goes and gets the number. It's in the Cursor marketplace and the official MCP Registry, and the catalog has grown past a hundred tools, though, as you'll see, no single session loads them all. What's actually connected Metrifyr isn't a wrapper around one API. It federates the whole Google marketing surface behind a single MCP connection: Analytics 4 : run reports, realtime, metadata, compare periods. Plus the admin side: create properties, data streams, conversion events, custom dimensions and metrics. Search Console : search analytics, URL inspection, sitemaps. AdSense : accounts, earnings, payment history, revenue by keyword. Tag Manager : read and audit containers, tags, triggers, variables. Google Ads : campaign planning. Connect it once, and the agent can reach across all of them in a single train of thought. "Which landing pages lost the most organic traffic last quarter, and were any of them earning AdSense revenue?" is one question to me. It's Search Console and Analytics and AdSense to the machine, joined without me opening a single tab. Raw numbers are the boring part Pulling a GA4 report over MCP is table stakes. The part I actually care about is the layer on top, the analysis tools that answer the questions you'd otherwise pay an SEO consultant to run: Content decay scan : which pages are quietly bleeding traffic month over month. Striking-distance optimizer : the queries ranking positions 11 to 20, one nudge away from page one. Keyword cannibalization : where two of your own pag

2026-08-04 原文 →
AI 资讯

Your MCP server's real constraint is the context window, not the API

We use AskElephant to record client calls, and we work in claude.ai. Those two things could not talk to each other, and the reason is structural rather than a missing feature. AskElephant ships an MCP server. It runs locally over stdio, which serves Claude Desktop, Cursor, VS Code and Windsurf. A browser cannot spawn a process on your laptop, so claude.ai needs an MCP server at an HTTPS address. That is a different program. Building it took about a day. Working out what it should refuse to do took considerably longer, and that part generalises to any MCP server sitting in front of a large corpus. The code is on GitHub . The arithmetic that determines the design Before writing tools, measure your payload. We measured every transcript in our account: 3,706 engagements, 2,230 of which carry one. Characters Approx tokens Average transcript-bearing call 32,485 8,100 Median 28,240 7,060 p95 75,543 18,885 Largest 175,643 43,900 The largest single call is more than a fifth of a 200,000-token context window on its own. Now consider the actual user request: "find where we discussed pricing with this client this year." That touches maybe forty calls. The naive tool returns forty transcripts, which is roughly 325,000 tokens. It does not fit. Not slow, not costly: impossible. So the design constraint is not the API. It is arithmetic, and it arrives before you write a single tool definition. Do the reading on the server The whole design collapses to one line: The Worker does the reading. Claude does the thinking. search_transcripts fetches the candidate transcripts, scans them inside the Worker, and returns only matching passages with speaker and timestamp attached. A real forty-meeting search, run through claude.ai against the live archive, returned 76,757 characters of excerpt: about 19,200 tokens rather than 325,000. The scanner is a pure function with no IO, which makes it trivial to test: export function scanTranscript ( text : string , queries : string [], opts : ScanOption

2026-08-04 原文 →
AI 资讯

The Backup Question Nobody Wants to Answer

Most companies we work with don't have a data inventory. When we ask "where's your data listed?" (where it lives, what it contains, who owns it), the answer is usually some version of "we don't have one." No comprehensive map of data locations. No business impact assessment for different data types. Unclear ownership and accountability. You can't protect what you haven't mapped. And you can't make good decisions about backup strategy when you don't know what you're backing up. Data Has a Half-Life Not all data ages the same way. Some data becomes stale quickly. If you're aggregating information from external sources like market data, business intelligence, or operational metrics, the value is often in the freshness. Yesterday's data might be useful for trends, but it's not the crown jewels. Source data and processed insights need different protection levels. The raw inputs you collect might be recreatable from upstream sources. The analysis and transformations you've built on top might take significant effort to reconstruct, or might be regenerated in hours if you have the pipeline intact. This changes the backup math. If your data pipeline gets destroyed but you can pull from upstream sources and recreate everything within an acceptable timeframe, maybe you don't need to back up the work product at all. Maybe you just need to protect the source data and the pipeline itself. Understanding your data's half-life helps you spend backup dollars where they actually matter. The Cost vs. Risk Conversation Backup costs can reach hundreds of thousands of dollars annually. Cross-region replication, long-term retention, disaster recovery infrastructure. It adds up fast. That's money not going to engineers or product development. A real tradeoff. The question is: what's the actual business impact if this data disappears? What's the downtime cost? What's your real risk tolerance? These are executive decisions, not just technical ones. They require someone to say "we're willing t

2026-08-04 原文 →
产品设计

Nothing CMF is launching its first open earbuds

Open earbuds are having a bit of a moment right now, and Nothing is the latest company jumping on the trend. Its budget sub-brand has introduced the CMF Clip Pro, CMF's first open-ear buds that are designed to provide comfort and sound quality for people who don't want to sacrifice their situational awareness. The $99 […]

2026-08-04 原文 →
开发者

Iter: programar desde la intención

Vista previa técnica: Iter todavía no está publicado en PyPI y no existe un paquete oficial instalable. Abrir un recurso, convertir datos o cambiar de backend suele exigir aprender una interfaz diferente y repetir código de integración. Iter nace de una idea sencilla: Aprende una vez. Usa cualquier biblioteca. iter convert data.json to data.csv El usuario expresa una sola intención. Iter se encarga de abrir el recurso, detectar los formatos, seleccionar un adaptador compatible, convertir los datos y guardar el resultado. Una intención. Una instrucción. ¿Qué busca cambiar Iter? Actualmente, una tarea sencilla puede exigir: importar bibliotecas; aprender APIs diferentes; configurar formatos manualmente; escribir código de integración; seleccionar cada backend. Con Iter, el usuario indica principalmente qué quiere conseguir: iter analyze sales.csv Iter selecciona automáticamente una herramienta compatible. Si el usuario necesita controlar la biblioteca, puede indicarla: iter analyze sales.csv with pandas La automatización es el comportamiento predeterminado. El control detallado sigue siendo opcional. Everything is a Resource Iter representa archivos, datos y recursos web mediante una estructura común llamada Resource . El sistema está organizado alrededor de cinco componentes: Resource : representa el recurso. Resolver : identifica formatos, tipos y backends. Registry : registra y selecciona adaptadores. Adapter : ejecuta operaciones concretas. Engine : coordina el proceso. La meta no es afirmar que todas las bibliotecas son idénticas. La meta es unificar intenciones comunes y conservar las diferencias importantes cuando sean necesarias. Estado actual Iter 0.3.0-rc.2 está en fase de corrección de errores y validación privada. Actualmente: el código principal permanece privado; Iter todavía no está publicado en PyPI; no existe un paquete demostrativo; la sintaxis puede ajustarse antes del lanzamiento; solamente se anunciarán como disponibles las funciones implementadas

2026-08-04 原文 →
开发者

JavaScript Interview Questions Every Dev Should Know — Part 2: Functions, Scope & Closures

Welcome to Part 2 of the JS interview series! This time we're tackling functions, scope, and the topic that trips up even experienced developers in interviews: closures . Missed Part 1? Check out Fundamentals & Data Types first. Q1. What is a closure? A closure is what happens when an inner function "remembers" and continues to have access to the variables from its enclosing (outer) function's scope, even after that outer function has already finished running and would normally have had its local variables cleaned up. This works because JavaScript functions don't just capture the values of outer variables — they capture live references to them, keeping the entire surrounding scope alive in memory for as long as the inner function itself is reachable. Closures are one of the most powerful and commonly used patterns in JavaScript. They're the mechanism behind data privacy (since variables inside a closure can't be accessed from outside except through the functions that were given access), factory functions that generate customized functions, memoization caches, and event handler callbacks that need to remember state from when they were created. In the classic counter example below, each call to counter() creates a fresh, independent count variable that only the returned function can see or modify — there's no way to reach into it from outside. function counter () { let count = 0 ; return () => ++ count ; } const inc = counter (); inc (); // 1 inc (); // 2 Q2. What is lexical scoping? Lexical scoping (also called static scoping) means that a variable's accessibility is determined entirely by where it's physically written in your source code — not by which function called which, or the order in which functions happen to execute at runtime. When JavaScript compiles your code, it can already determine, just by looking at the nesting of functions and blocks, exactly which variables any given piece of code will be able to see. This is what allows an inner function to "reach

2026-08-04 原文 →
开发者

Apple briefly yanked Telegram from the App Store over CSAM violations

Telegram is back on the App Store after Apple briefly removed it on Monday night over concerns about child sexual abuse material (CSAM). In a statement to Bloomberg's Mark Gurman, Apple says a review found that Telegram "violates our strict guidelines prohibiting child sexual abuse material," adding that it restored the app "after the developer […]

2026-08-04 原文 →
AI 资讯

Scope Is Never Fixed — Why Specification Ambiguity (Not Scope Creep) Is the Real Fixed-Price Problem

Software projects fail on fixed-price contracts. This is not a controversial statement — the Standish Group's CHAOS report has tracked this for decades, showing that only 31% of software projects succeed on time and on budget, while 50% are challenged and 19% fail outright. But the conventional wisdom about why they fail — scope creep — misses the real problem. Scope creep is a symptom. The real disease is specification ambiguity . The Map Is Not the Territory Paweł Brodziński, an experienced software delivery leader, captured this perfectly with a simple analogy. A specification is a map of the software you want to build. And as with any map, its representation of the terrain is necessarily imperfect. For a perfect map, it would have to be as large as the terrain itself. "The only absolutely precise specification of a software project is the code itself. But if you already have that, why would you buy it?" When you write "As a workspace owner, I can set administrative privileges to workspace members," two people reading that sentence will envision different things. One imagines a simple dropdown with three permission levels. The other imagines role-based access control with custom policies, audit logs, and delegation. Both are reasonable interpretations of the same text. The PMI's research on communications complexity confirms why this happens: the number of communication paths grows geometrically with project size ( n(n-1)/2 ), and every path is a channel where ambiguity can creep in. Even a simple conversation involves encoding, decoding, and filtering — two receivers can interpret the same message differently. Why This Is Not Scope Creep Scope creep is when a client asks for something new after the contract is signed. That's a well-understood problem with well-understood countermeasures: change requests, sign-offs, contingency buffers. Specification ambiguity is different. It's not about adding new things — it's about both parties believing they agreed on the sa

2026-08-04 原文 →
AI 资讯

The Art of Range Pricing in Software Projects: A Practical Guide for Agencies

Every software agency has been here: the client asks for a price, you give a range (say $45k–$65k), and two things can happen. Either the client nods and you win the deal at the low end — or they get suspicious and ask "so you don't actually know how much it costs?" Range pricing is often misunderstood. Used wrong, it looks like you're guessing. Used right, it's the most honest and professional way to price software projects — because anyone who gives you a single fixed number for an undefined project is either padding heavily or gambling with their margin. This guide covers when to use range pricing, how to structure it, and — most importantly — how to present it so clients trust you more, not less. Why Single-Point Pricing Is a Problem A fixed price for an undefined project forces you into one of two positions: You pad aggressively — add 40% contingency, quote $70k for a project you'd happily do for $50k. If the scope doesn't expand, the client overpays. If it does, you're protected. Either way, one party loses. You guess lean — quote $50k based on your best assumptions. If the client adds features mid-project, your margin evaporates. The client thinks they're paying for X, you're building X+Y. Both parties end up frustrated. A pricing range avoids both traps. It says: "based on what we know today, this project falls between $45k and $65k. Here's what needs to be true for the low end, and here's what would push it toward the high end." That's not guesswork. That's transparency. The Anatomy of a Good Pricing Range Not all ranges are created equal. A useful range has three properties: 1. Width That Respects Uncertainty The width of your range communicates how well you understand the project. Range width What it signals When it's appropriate < 15% ($50k–$57k) High confidence Detailed spec, similar past projects, known team 15–30% ($50k–$65k) Moderate confidence Clear brief, some unknowns in tech or integration 30–50% ($50k–$75k) Low confidence Vague brief, new domain

2026-08-04 原文 →