samsin33/laravel-foundation

此包为 Laravel 提供基础,以更平滑地使用其功能。

v1.2.2 2023-07-15 18:43 UTC

This package is auto-updated.

Last update: 2024-09-16 00:37:49 UTC


README

为 Laravel 9 和 10 版本提供的基座包。此包为 Laravel 提供基座,以更平滑地使用其功能。

安装

只需使用 composer 安装 samsin33/laravel-foundation 包。

$ composer require samsin33/laravel-foundation

基座模型

此包旨在以最酷的方式使用 Eloquent 功能。
要创建模型,请使用 foundation:make-model 命令。此命令还会接受额外的属性,如 --controller 等,这些属性在 Laravel 文档中有介绍。

$ php artisan foundation:make-model Post

Post 模型将创建在您的 app/Models 文件夹中,它扩展了 Samsin33\Foundation\Models\BaseModel 类。
Samsin33\Foundation\Models\BaseModel 类扩展了 Illuminate\Database\Eloquent\Model 类,因此您可以使用 Eloquent 模型的所有功能。

重要性

基座模型以非常简单的方式执行以下功能。

验证

要为模型创建验证,只需定义 getValidationRules() 函数即可,它应返回验证数组。
要定义自定义验证消息,请定义 getValidationMessages() 函数,它也将返回验证消息数组。
要获取错误消息,请使用 Eloquent 对象的 errors() 方法,例如 $post->errors()->all()。

有时如果您不想验证数据,请使用 saveWithoutValidate()。有时我们希望有条件地验证一些字段,例如密码、状态等。在这种情况下,请使用 setValidationType()、removeValidationType() 和 isValidationType()。

注意:验证发生在保存事件中,所以每次在创建或更新 Eloquent 对象时都会调用。

use Samsin33\Foundation\Models\BaseModel;

class Post extends BaseModel
{
    protected function getValidationRules(): array
    {
        $arr = [
          'title' => ['required', 'max:255'],
          'description' => ['required']
        ];
        if ($this->isValidationType('check_status')) {
          $arr['status'] = ['required', 'integer'];
        }
        return $arr;
    }

    protected function getValidationMessages(): array
    {
        return [
          'title.required' => 'A title is required',
          'title.max' => 'Title should be maximum of 255 length',
          'description.required' => 'A description is required'
        ];
    }
}

// You can get errors from model objects. In controller function write code:

function save(Request $request) {
    $post = new Post(['title' => $request->title, $request->description]);
    if (some condition) {
      $post->setValidationType('check_status');
    }
    if ($post->save()) {
    } else {
      $post->errors()->all();
      // or
      $post->showErrors();
      // Other validation functions can also apply check laravel validation documentation.
    }
    // If you want to remove any set validation type use
    $post->removeValidationType('check_status');
    
    // if no validation required then do:
    $post->saveWithoutValidate();
}

事件

Laravel Eloquent 有 14 个事件:retrieved、creating、created、updating、updated、saving、saved、deleting、deleted、trashed、forceDeleted、restoring、restored 和 replicating。要在模型中使用事件,只需定义事件名称后跟 Event 函数即可。例如 savingEvent()、updatedEvent()、deletingEvents()。

在 *ing 事件 中,如果返回 false,则操作将停止。

注意:验证发生在 savingEvent() 中,所以请在该处调用 parent::savingEvent() 并确保如果 parent::savingEvent() 为 false,则返回 false。

use Samsin33\Foundation\Models\BaseModel;

class Post extends BaseModel
{
  public function savingEvent()
    {
        if (parent::savingEvent()) {
             // do something
             return $this;
        }
        return false;
    }
    
    // To delete all comments if the post is deleted
    public function deletedEvent()
    {
        Comment::where('post_id', $this->id)->delete();
    }
}

队列

如果您想将某些内容推送到队列,请调用 dispatchQueue()。此函数将接受两个参数,第一个参数是函数名称,第二个参数是数据数组。
您需要定义具有第一个参数中给出的名称的函数,并使用 $data 参数。
如果您想在 post delete() 被调用时使用当前用户属性,请使用 $this->queue_user 属性。
在上面的示例中,让我们将所有帖子评论删除到队列中。

use Samsin33\Foundation\Models\BaseModel;

class Post extends BaseModel
{
  // To delete all comments if the post is deleted
    public function deletedEvent()
    {
        $addition_data = ['some_data'];
        $this->dispatchQueue('deletePostComments', $addition_data);
    }

    // This function will be called once the queue is executed.
    public function deletePostComments($data)
    {
        // $data will have $addition_data values
        Comment::where('post_id', $this->id)->delete();
        // To access the current user details at the time post delete() is called use $this->queue_user attribute.
        $user = $this->queue_user;
    }
}

缓存

CacheTrait 包含非常实用的函数,使得缓存变得非常简单。
假设有一个 Category 模型,您想缓存活动和非活动分类。
您需要更新 $is_cached、$cache_fields、$cache_conditions 属性。

$is_cached 应设置为 true,如果需要为该模型启用缓存。
$cache_fields 包含需要从 getCache() 中获取的属性。
并且 $cache_conditions 必须是一个数组,其中数组的键是缓存键,其值也应该是需要传递到 where 条件的数组。以下是一个示例。

use Samsin33\Foundation\Models\BaseModel;

class Category extends BaseModel
{
  protected static bool $is_cached = true;
  protected static $cache_fields = ['id', 'name', 'status'];
  protected static $cache_conditions = ['active' => ['status' => 1], 'inactive' => ['status' => 0]];
}

// To get cached values
Category::getCache('active');
Category::getCache('inactive');

// To set cache values
Category::setCache('active');
Category::setAllCache();

// To delete cache values
Category::destroyCache('inactive');
Category::destroyAllCache();

// resetAllCache function will reset all cache_conditions data of model.
Category::resetAllCache();

邮件

MailerTrait 包含 sendMail() 方法,用于发送邮件。此函数需要以下参数:
$email_to,
string $view,
string $subject = '', (可选)
array $data = [], (可选)
array $cc = [], (可选)
array $bcc = [], (可选)
int $reset_email_from = 0, (可选)
array $attach = [], (可选)
array $reply_to = []. (可选)

在视图文件中,你可以通过 $data 变量访问属性。
$data 将包含 2 个键
$data['object'] - 包含模型对象。
$data['other_data'] - 包含在 sendMail() 中传递的上述 $data 参数的值。

你也可以通过使用 sendExceptionEmail() 函数发送异常邮件,此时你需要在邮件配置文件中添加 exception_email 键。
第一个参数接受 $exception 变量,该变量可以是一个数组。在视图文件中,$exception 数据将作为 $data['other_data'] 可用。

注意:你也可以在 Exceptions/Handler.php 文件中使用 MailerTrait 来调用异常邮件函数。

config/mail.php
return [
  'exception_email' => 'email_to_receive_exception@mail.com'
];

Exceptions/Handler.php
$this->reportable(function (Throwable $exception) {
    $this->sendExceptionEmail(['exception' => $exception->getTraceAsString(), 'exception_view_blade_file']);
});

其他特性

一些其他有用的特性包括
UserSessionTrait
RequestTypeTrait
DateTrait
GuzzleHttpTrait

要获取当前用户详情,可以使用
currentUser()
currentUserId()

你可以查看其他特性以使用它们的函数。