tebe / yii2-inertia
Inertia.js的Yii 2适配器
v1.1.0
2024-07-24 11:37 UTC
Requires
- php: >=5.6.0
- ext-json: *
This package is auto-updated.
Last update: 2024-09-24 11:59:42 UTC
README
这是Inertia的Yii 2服务器端适配器。
使用Inertia,您可以使用经典的服务器端路由和控制器来构建单页面应用,而不需要构建API。
要使用Inertia,您需要服务器端适配器和客户端适配器。
请确保遵循您使用的客户端框架的安装说明。
演示
安装
Composer依赖项
composer require tebe/yii2-inertia
编辑config/web.php
<?php return [ ... 'bootstrap' => ['inertia'] ... 'components' => [ 'inertia' => [ 'class' => 'tebe\inertia\Inertia' 'rootElementId' => 'app' // optional per https://inertia.laravel.net.cn/client-side-setup#defining-a-root-element ], 'request' => [ 'cookieValidationKey' => '<cookie_validation_key>', 'enableCsrfValidation' => false, 'enableCsrfCookie' => false, 'parsers' => [ 'application/json' => 'yii\web\JsonParser', ] ] ] ... ];
注意CSRF保护已禁用。
控制器
您的后端控制器应扩展自tebe\inertia\web\Controller
。在您的动作中,您应使用inertia
方法代替render方法。
<?php namespace app\controllers; use tebe\inertia\web\Controller; class DemoController extends Controller { public function actionIndex() { $params = [ 'data' => [], 'links' => [] ]; return $this->inertia('demo/index', $params); } }
路由
像往常一样使用您的Yii服务器端路由。没有特殊之处。
CSRF保护
Axios是Inertia在底层使用的HTTP库。Yii的CSRF保护没有针对Axios进行优化。
实现CSRF保护的最简单方法是使用定制的tebe\inertia\web\Request
组件。只需编辑config/web.php
文件
<?php return [ 'components' => [ 'request' => [ 'class' => 'tebe\inertia\web\Request', 'cookieValidationKey' => '<cookie_validation_key>' ] ] ];
请参阅安全页面以获取更多详细信息。
共享数据
Yii 2适配器提供了一种为每个请求预分配共享数据的方法。这通常在您的控制器之外完成。共享数据将与控制器中提供的页面props自动合并。
共享数据的批量赋值
<?php $shared = [ 'user' => [ 'id' => $this->getUser()->id, 'first_name' => $this->getUser()->firstName, 'last_name' => $this->getUser()->lastName, ], 'flash' => $this->getFlashMessages(), 'errors' => $this->getFormErrors(), 'filters' => $this->getGridFilters() ]; Yii::$app->get('inertia')->share($shared);
一个键的共享数据
<?php $user = [ 'id' => $this->getUser()->id, 'first_name' => $this->getUser()->firstName, 'last_name' => $this->getUser()->lastName ]; Yii::$app->get('inertia')->share('user', $user);
当在控制器之外使用共享数据时,一个好的策略是实现一个动作过滤器。
<?php namespace app\components; use yii\base\ActionFilter; class SharedDataFilter extends ActionFilter { public function beforeAction() { $shared = [ 'user' => $this->getUser(), 'flash' => $this->getFlashMessages(), 'errors' => $this->getFormErrors() ]; Yii::$app->get('inertia')->share($shared); return parent::beforeAction($action); } }
然后使用此动作过滤器作为控制器中的行为。
<?php namespace app\controllers; use app\components\SharedDataFilter; use tebe\inertia\web\Controller; class ContactController extends Controller { public function behaviors() { return [ [ 'class' => SharedDataFilter::class ] ]; } public function actionIndex() { // your action code } }
请参阅共享数据页面以获取更多详细信息。
客户端设置
要使用Inertia,您需要设置客户端框架。这主要涉及更新主JavaScript文件以启动Inertia应用。请参阅客户端设置页面以获取更多详细信息。
关于Inertia的更多信息
访问inertiajs.com了解更多信息。