Inertia
此内容尚不支持你的语言。
Connect Yii requests, responses, views, sessions, and redirects to the Inertia protocol
Architecture
Section titled “Architecture”php-forge/inertia owns the Inertia protocol, page model, prop resolution,
headers, redirects, and result objects. This package connects that core to Yii requests, responses, views, and sessions.
The application supplies its JavaScript client, component resolver, and asset build.
Installation
Section titled “Installation”Applications on Yii 2.0 need a Bower asset source such as Asset Packagist; the installation guide covers it.
composer require yii2-extensions/inertia:^0.6See the installation guide for Yii development-line resolution, bootstrap registration, CSRF configuration, and frontend setup.
Quick start
Section titled “Quick start”A billing application: an invoice list with filters, totals that load after the page is on screen, a form that reports validation errors, and a checkout hosted by a payment provider.
Register the adapter in the existing web application configuration:
use yii\inertia\{Bootstrap, Manager};use yii\inertia\web\Request;use yii\web\JsonParser;
return [ 'bootstrap' => [Bootstrap::class], 'components' => [ 'inertia' => [ 'class' => Manager::class, // Changes with the build output. An Inertia GET from an outdated client gets a 409 and reloads the page. 'version' => static fn(): string => (string) hash_file( 'sha256', Yii::getAlias('@webroot/build/manifest.json'), ), // Sent with every page. A partial reload that does not ask for `auth` never runs the closure. 'shared' => [ 'auth' => [ 'user' => static fn(): array|null => Yii::$app->user->isGuest ? null : ['id' => Yii::$app->user->getId()], ], ], ], 'request' => [ // Reads the CSRF token from the X-XSRF-TOKEN header, which the client fills from the XSRF-TOKEN cookie. 'class' => Request::class, 'cookieValidationKey' => getenv('COOKIE_VALIDATION_KEY'), 'parsers' => ['application/json' => JsonParser::class], ], ],];Return pages and ordinary Yii redirects from the controller:
use Yii;use yii\filters\VerbFilter;use yii\inertia\Inertia;use yii\inertia\web\Controller;use yii\web\Response;
final class InvoiceController extends Controller{ public function behaviors(): array { return [ 'verbs' => [ 'class' => VerbFilter::class, 'actions' => ['create' => ['POST'], 'delete' => ['DELETE']], ], ]; }
public function actionIndex(string $status = 'open'): Response { return $this->inertia( 'Invoices/Index', [ 'filters' => ['status' => $status], // A closure runs only when its prop is sent: a partial reload asking for `totals` skips this query. 'invoices' => static fn(): array => Invoice::find()->where(['status' => $status])->asArray()->all(), // Left out of the first response. The client fetches it once the page is on screen. 'totals' => Inertia::defer( static fn(): array => ['outstanding' => Invoice::find()->where(['status' => 'open'])->sum('amount')], ), // Sent once, then kept by the client for an hour and left out of its later visits. 'currencies' => Inertia::once(static fn(): array => Currency::find()->select('code')->column()) ->until(3600), // Resolved only when a partial reload names it, such as when the user opens the history panel. 'history' => Inertia::optional(static fn(): array => AuditLog::find()->limit(20)->asArray()->all()), ], ); }
public function actionCreate(): Response { $invoice = new Invoice();
$invoice->load($this->request->post(), '');
if (!$invoice->save()) { // The `errors` flash becomes `props.errors` on the page that follows the redirect. Yii::$app->session->setFlash('errors', $invoice->getErrors());
return $this->redirect(['index']); }
// Every other flash arrives in the page's top-level `flash` field. Yii::$app->session->setFlash('success', 'Invoice created.');
return $this->redirect(['index']); }
public function actionDelete(int $id): Response { Invoice::findOne($id)?->delete();
// Yii answers 302. For an Inertia DELETE, PUT or PATCH the adapter sends 303, so the client follows with GET. return $this->redirect(['index']); }
public function actionPay(int $id): Response { // Leaves the application: 409 with X-Inertia-Location for an Inertia visit, a plain 302 otherwise. return $this->location("https://pay.example.com/checkout/{$id}"); }}The first visit to /invoice/index returns the HTML document with the page embedded as JSON. The client’s next visit
carries X-Inertia: true and receives only the page:
{ "component": "Invoices/Index", "props": { "auth": { "user": { "id": 1 } }, "filters": { "status": "paid" }, "invoices": [{ "id": 7, "status": "paid", "amount": 120 }], "currencies": ["EUR", "USD"], "errors": {} }, "url": "/invoice/index?status=paid", "version": "1796120000", "deferredProps": { "default": ["totals"] }, "sharedProps": ["auth"], "onceProps": { "currencies": { "prop": "currencies", "expiresAt": 1796123600000 } }}totals and history are absent: the client requests totals in a partial reload as soon as the page renders, and
history only when the component asks for it. After a rejected actionCreate(), the same page arrives with
"errors": { "amount": ["Amount cannot be blank."] }.
The default root view carries the page payload but loads no frontend bundle. The Configuration Guide covers the application-owned root view and the CSRF cookie, and the Usage Examples cover merge and infinite-scroll props.
Documentation
Section titled “Documentation”Practical guides and examples for page responses, shared props, and form validation.
- 📚 Installation guide: Composer, bootstrap, CSRF, and frontend setup.
- ⚙️ Configuration and adapter reference: manager options, props, root views, and responses.
- 💡 Usage examples: controllers, prop recipes, validation, and redirects.
- 🔄 Upgrade guide and migration guide: application changes for existing installations.
- 🧪 Testing guide: PHPUnit, static analysis, mutation, and documentation checks.
The guides and the API reference generated from
the PHPDoc in src/ are published at https://yii2-framework.github.io/docs/extensions/inertia/.
AI assistance
Section titled “AI assistance”AI agents: read the documentation index and fetch the Markdown version
of a page by appending index.md to its URL. The
AI agents guide covers skill installation, client setup and
verification.
- 🤖
yii2-inertia-integrationskill: Yii 22 adapter setup, root views, props, validation flashes, signed CSRF cookies, redirects, observers and 0.1 upgrades. - 🧭
yii2-frameworkskill: Yii 22.0 application conventions.
The hosted documentation covers Yii 22.0. If it does not match the installed revision or is unavailable, use the repository guides, the skill source, the source PHPDoc and the changelog.
Our social networks
Section titled “Our social networks”Follow on X Follow on Facebook Join our Subreddit Join on Telegram
License
Section titled “License”Package
Section titled “Package”- Source code and issues: yii2-extensions/inertia. Star the repository if the package is useful to you.
- Composer package: yii2-extensions/inertia.
- Changelog: CHANGELOG.md.