parziphal/parse

Parse 的一个类似 Eloquent 的接口

v0.0.8 2020-05-04 21:45 UTC

README

这个库试图以类似 Eloquent 的方式使用 Parse。适用于 Laravel 5.2 及以上版本。

功能

  • 自动初始化 Parse。
  • 使用封装 Parse 类的 facade 类,暴露类似 Eloquent 的接口。
  • 支持与 Parse 的关系一起工作。
  • 用户认证,支持用户名/密码组合以及 Facebook 认证。
  • 创建 ObjectModel 的命令(artisan parse:model SomeModel)。

安装

使用 Composer 安装库

composer require parziphal/parse

将服务提供者在你的 config/app.php 文件中添加

'providers' => [
    // etc...
    Parziphal\Parse\ParseServiceProvider::class,
],

运行以下命令以发布配置文件

php artisan vendor:publish --tag=parse

该命令将在 config/parse.php 文件中创建一个文件,您可以在此设置您的 Parse 服务器配置。但是,而不是编辑该文件,您可以通过设置以下变量在您的 .env 文件中设置配置

PARSE_APP_ID=Your_App_ID
PARSE_REST_KEY=REST_API_key
PARSE_MASTER_KEY=Master_key
PARSE_SERVER_URL=http://127.0.0.1:1337
PARSE_MOUNT_PATH=/parse

REST_API_key 变量是可选的,因为 Parse 已经不再需要该密钥。

ObjectModel

创建扩展 Parziphal\Parse\ObjectModel 类的模型

namespace App;

use Parziphal\Parse\ObjectModel;

class Post extends ObjectModel
{
}

就是这样。但是,请记住,您可以使用 Artisan 命令 php artisan parse:model SomeModel 简单地创建一个模型。

ObjectModel 的行为就像 Eloquent 模型一样,因此您可以执行类似以下操作

// Instantiate with data
$post = new Post(['title' => 'Some Title']);

// Create
$post = Post::create(['title' => 'Some Title', 'acl' => $acl]);

// Get objectId
echo $post->id;   // EWFppWR4qf
echo $post->id(); // EWFppWR4qf

// Update
$post->title = 'New Title';
$post->save();
// or
$post->update(['foo' => true]);

// Find or fail
$post = Post::findOrFail($id);

// Delete is like Eloquent's delete: it will delete the object
$post->delete();
// To remove a key (ParseObject's `delete` method), use `removeKey`
$post->removeKey($someKey);

// Create a pointer object
$pointer = Post::pointer($postId);

关系

支持的关联有

  • belongsTo 和其对应 hasMany
  • belongsToMany,它将父级 ID 存储在数组中,及其对应 hasManyArray

您可以使用它们像这样

use Parziphal\Parse\ObjectModel;

class Post extends ObjectModel
{
    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

// Having the above class where categories() is a `belongsToMany` relation,
// the class Category would have a posts() relation of type `hasManyArray`:
class Category extends ObjectModel
{
    public function posts()
    {
        return $this->hasManyArray(Post::class);
    }
}

// This would be the User class:
class User extends ObjectModel
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

// Relate a post with a category (belongsToMany):
$post->categories()->save($someCategory);

// Relate a category with posts (inverse of above, hasManyArray):
$category->posts()->save($post);
$category->posts()->create($arrayWithPostData);

// Relate a post with a user (belongsTo):
$post->user = $user;
$post->save();

// Relate a use with a post (inverse of above, hasMany):
$user->posts()->create($arrayWithPostData);

查询

Parziphal\Parse\QueryParse\ParseQuery 的包装器,它也像 Eloquent Builder 一样工作

// Note that `get` is like Eloquent Builder's `get`, which executes the query,
// and not like ParseQuery's `get` which finds an object by id.
$posts = Post::where('createdAt', '<=', $date)->descending('score')->get();

$posts = Post::where([
    'creator' => $user,
    'title' => $title
  ])
  ->containedIn('foo', $foos)
  ->get();

$post = Post::firstOrCreate($data);

// Load relations (ParseQuery::include())
$posts = Post::with('creator', 'comments.user')->get();

使用主密钥

对象和查询可以通过 $useMasterKey 属性配置为使用主密钥。这可以在类级别、实例化时或使用设置方法完成

// In objects, pass a second parameter when instantiating:
$post = new Post($data, true);
// or use the setter method:
$post->useMasterKey(true);

// Passing an anonymous function will set useMasterKey to true,
// then execute the function, then useMasterKey will be set to false.
$post->useMasterKey(function($post) {
    $post->increment('views')->save();
});

// When creating queries, pass as parameter:
$query = Post::query(true);
// or use the setter method:
$query->useMasterKey(true);

// Other object methods that accept a $useMasterKey value are:
$post  = Post::create($data, true);
$posts = Post::all(true);

// To configure a single model to _always_ use master key, define
// a protected static property `$defaultUseMasterKey`:
class Post extends ObjectModel
{
    protected static $defaultUseMasterKey = true;
}

// Finally, you can make all models use master key with this:
Parziphal\Parse\ObjectModel::setDefaultUseMasterKey(true);

使用 Parse 登录

注意:在 Laravel 5.4 中,web 中间件组有一个 \Illuminate\Session\Middleware\AuthenticateSession(默认情况下是禁用的)的条目。激活此中间件会导致“记住我”功能失败。

确保您的 User 类扩展 Parziphal\Parse\UserModel。您也可以从 Parziphal\Parse\Auth\UserModel 扩展,这是一个已准备好认证的用户类

namespace App;

use Parziphal\Parse\Auth\UserModel;

class User extends UserModel
{
}

现在我们必须配置 web 守卫和用户提供者,所以打开 config/auth.php,并进行以下更改

    'guards' => [
        'web' => [
            'driver' => 'session-parse',
            'provider' => 'users',
        ],
        // ...
    ],

    'providers' => [
        'users' => [
            'driver' => 'parse',
            'model'  => App\User::class,
        ],
        // ...
    ],

有 3 个提供者驱动可用

  • parse,它要求用户具有用户名和密码
  • parse-facebook,它要求用户使用他们的 Facebook 账户进行身份验证
  • parse-any,它允许用户使用用户名/密码或 Facebook 进行身份验证

使用 Facebook 登录

您可以在您的 auth 控制器中结合使用 Parziphal\Parse\Auth\AuthenticatesWithFacebook 特性以及 Laravel 的 Illuminate\Foundation\Auth\AuthenticatesUsers 特性。AuthenticatesWithFacebook 特性包含处理 Facebook 身份验证/注册的方法。只需将方法(或方法)绑定到路由即可。

以下是身份验证/注册特性的接口。请注意,它可以以两种方式响应:重定向(*Redirect 方法),或以 JSON(*Api 方法)响应,这将响应 $apiResponse 数组,该数组可用于自定义。

trait AuthenticatesWithFacebook
{
    protected $apiResponse = ['ok' => true];

    public function logInOrRegisterWithFacebookApi(Request $request);

    public function logInOrRegisterWithFacebookRedirect(Request $request);

    public function registerWithFacebookApi(Request $request);

    public function registerWithFacebookRedirect(Request $request);

    public function registerAny(Request $request);

    public function logoutApi(Request $request);

    // For logout with redirection simply use logout().
}

该特性期望找到用户的Facebook ID作为id参数,以及他们的访问令牌作为access_token参数。

使用用户名/密码登录

关于这一点需要考虑一些事项

  • Laravel默认注册控制器中由validator方法返回的验证器在email参数上有一个unique约束,这会导致数据库搜索,从而引发错误;请确保删除该unique约束。

  • 您还需要根据您的需求更改create方法。它可能看起来像这样

protected function create(array $data)
{
    $user = new User();
    $user->name = $data['name'];
    $user->username = $data['email'];
    $user->password = $data['password'];
    $user->signUp();

    return $user;
}

请注意,电子邮件被存储为用户名,这是因为Parse中,username字段是用户的登录名,所以如果您要求用户使用他们的电子邮件登录,您必须将他们的电子邮件存储在username键下。

灵感来源于

许可

MIT