ifnot/eloquent-vuex

此包已被弃用,不再维护。未建议替代包。

dev-master 2018-07-30 12:53 UTC

This package is auto-updated.

Last update: 2020-02-05 23:18:30 UTC


README

在 Vuex (VueJs) 和 Eloquent (Laravel) 之间进行实时模型同步

此包允许您通过 Laravel Echo 将 Eloquent 事件(创建、更新和删除)发送为 Vuex 突变,以保持所有客户端数据与 Laravel 数据库同步。

此包旨在方便地集成,无需对 Laravel 后端和 Vuex 前端进行深度更改。

先决条件

在开始使用此包之前,您应该有一个可工作的 Echo 安装(客户端+服务器)。请遵循文档中的官方安装步骤。您必须能够从 Laravel 发送一个 ping 并通过 Echo 读取它。

安装

composer require ifnot/eloquent-vuex

由于这是一个 WIP,您可能需要在您的 composer.json 中降低稳定性选项

"minimum-stability": "dev",
"prefer-stable": true

然后将服务提供者添加到您的 config/app.php 中,在您的应用程序服务提供者之前(重要)

Ifnot\EloquentVuex\Providers\EloquentVuexServiceProvider::class,

快速入门

在您的 AppServiceProvider 中监听 Eloquent 模型的修改

use Ifnot\EloquentVuex\Vuex;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Vuex::sync([
            App\Car::class
        ]);
    }
}

微调

在您的模型中引用一个 $store 属性以更改默认事件广播行为

class Car extends Model
{
    public $store = CarStore::class;
    
    // ...
}

class CarStore extends Ifnot\EloquentVuex\Vuex\Store
{
    public function getCascadeRelations(): array
    {
        // Return relations to be updated when this model changes
        // Example : if we have $car->user, the following line will update the related model for every changes
        return ['users'];
    }
    
    public function getNamespace(): string
    {
        // Changes the default module name on the client-side
        return 'MyCars';
    }
    
    public function toArray(Model $model): array
    {
        // How the model is converted to event payload
        // Example : a savage way to call a fractal transformer
        $fractal = new \League\Fractal\Manager();
        $resource = new \League\Fractal\Resource\Item($model, new CarTransformer());
        return $fractal->createData($resource)->toArray()['data'];
    }
    
    public function getStates(Model $model): array
    {
        // Which state to be mutated on the client side
        // Example : use a private channel instead the public one
        // To be documented : there is many other states for your app logic
        return [
            new \Ifnot\EloquentVuex\Vuex\States\State($this, 'all', new Illuminate\Broadcasting\PrivateChannel('my-private'))
        ];
    }
}

请记住,您可以通过阅读默认 Store 实现来查看默认行为