tricki/laravel-notification

Laravel 4 的基本用户通知包

dev-master 2015-12-23 08:00 UTC

This package is not auto-updated.

Last update: 2024-09-28 15:51:23 UTC


README

为 Laravel 4 提供一个灵活的用户通知系统的基本起点。

它很容易通过新的通知类型进行扩展,并完全由您决定渲染方式。

此包仅提供可扩展的通知系统,不包含任何控制器或视图,因为它们通常非常特定于用例。

我愿意考虑扩展此包的想法。

安装

1. 使用 Composer 安装

composer require tricki/laravel-notification:@dev

这将更新 composer.json 并将其安装到 vendor/ 目录中。

(请参阅 Packagist 网站 获取可用版本号和开发版本列表。)

2. 在 config/app.php 中添加提供者

    'providers' => [
        // ...
        'Tricki\Notification\NotificationServiceProvider',
    ],

这将在 Laravel 中注册包并自动创建一个名为 Notification 的别名。

3. 发布配置

如果您的模型是命名空间化的,您必须在包配置中声明这一点。

使用 Artisan 发布包配置

php artisan config:publish tricki/laravel-notification

将新创建的 app/config/packages/tricki/laravel-notification/config.php 中的 namespace 属性设置为通知模型的命名空间。

示例

'namespace' => '\MyApp\Models\'

4. 执行迁移

php artisan migrate --package="tricki/laravel-notification"

5. 将关系添加到 User

使用以下关系扩展您的 User 模型

	public function notifications()
	{
		return $this->hasMany('\Tricki\Notification\Models\NotificationUser');
	}

使用方法

1. 定义通知模型

您将需要为每种类型的通知分别创建模型。一些示例可以是 PostLikedNotificationCommentPostedNotification

这些模型定义了每种通知类型的独特行为,如它的操作和渲染。

一个最小的通知模型如下所示

<?php

class PostLikedNotification extends \Tricki\Notification\Models\Notification
{
	public static $type = 'post_liked';
}

类型将被保存在数据库中以区分不同类型。类名 必须 是此类型的驼峰版本并以 "Notification" 结尾。

请记住将您的通知模型的命名空间添加到此包的 config.php

2. 创建一个通知

可以使用 Notification::create 创建通知。

该函数接受 5 个参数

  • $type 字符串 通知类型(见 定义通知模型
  • $sender 模型 发起通知的对象(用户、组、网络服务等)
  • $object 模型 | NULL 被更改的对象(被点赞的帖子)
  • $users 数组 | Collection | User 应该接收此通知的用户(们)
  • $data 混合 | NULL 您想附加的任何其他数据。这将被序列化到数据库中。

3. 获取用户的提醒

您可以使用 notifications 关系获取发送给用户的提醒集合,这将返回您的通知模型集合。

您可以轻松获取发送给用户的全部通知集合

$user = User::find($id);
$notifications = $user->notifications;

您也可以使用 readunread 范围分别获取已读或未读通知

$readNotifications = $user->notifications()->read()->get();
$unreadNotifications = $user->notifications()->unread()->get();

由于通知是您自己的模型实例,因此您可以轻松地为每种通知类型提供不同的行为或输出。

示例

<?php

class PostLikedNotification extends \Tricki\Notification\Models\Notification
{
	public static $type = 'post_liked';

	public function render()
	{
		return 'this is a post_liked notification';
	}
}

class CommentPostedNotification extends \Tricki\Notification\Models\Notification
{
	public static $type = 'comment_posted';

	public function render()
	{
		return 'this is a comment_posted notification';
	}
}
?>
// notifications.blade.php

<ul>
	@foreach($user->notifications as $notification)
	<li>{{ $notification->render() }}</li>
	@endforeach
</ul>

这可能输出

<ul>
	<li>this is a post_liked notification</li>
	<li>this is a comment_posted notification</li>
</ul>