资讯专栏INFORMATION COLUMN

Laravel Taggable 为你的模型添加打标签功能

lucas / 410人阅读

摘要:标签名称规则说明标签名里的特殊符号和空格会被替代智能标签生成,会生成对应的中文拼音,如标签,拼音一样的时候会被加上随机值标签名清理使用。

本文经授权转自 PHPHub 社区

功能说明

使用最简便的方式,为你的数据模型提供强大「打标签」功能。

项目地址:https://github.com/summerblue/laravel-taggable

本项目修改于 rtconner/laravel-tagging 项目,增加了一下功能:

标签名唯一;

增加 etrepat/baum 依赖,让标签支持无限级别标签嵌套;

中文 slug 拼音自动生成支持,感谢超哥的 overtrue/pinyin;

提供完整的测试用例,保证代码质量。

注意: 本项目只支持 5.1 LTS

此项目由 The EST Group 团队的 @Summer 维护。

无限级别标签嵌套

集成 etrepat/baum 让标签具备从属关系。

$root = Tag::create(["name" => "Root"]);

// 创建子标签
$child1 = $root->children()->create(["name" => "Child1"]);

$child = Tag::create(["name" => "Child2"]);
$child->makeChildOf($root);

// 批量构建树
$tagTree = [
    "name" => "RootTag",
    "children" => [
        ["name" => "L1Child1",
            "children" => [
                ["name" => "L2Child1"],
                ["name" => "L2Child1"],
                ["name" => "L2Child1"],
            ]
        ],
        ["name" => "L1Child2"],
        ["name" => "L1Child3"],
    ]
];

Tag::buildTree($tagTree);

更多关联操作请查看:etrepat/baum 。

标签名称规则说明

标签名里的特殊符号和空格会被 - 替代;

智能标签 slug 生成,会生成 name 对应的中文拼音 slug ,如:标签 -> biao-qian,拼音一样的时候会被加上随机值;

标签名清理使用:$normalize_string = EstGroupeTaggableUtil::tagName($name)

Tag::create(["标签名"]);
// name: 标签名
// slug: biao-qian-ming

Tag::create(["表签名"]);
// name: 表签名
// slug: biao-qian-ming-3243 (后面 3243 为随机,解决拼音冲突)

Tag::create(["标签 名"]);
// name: 标签-名
// slug: biao-qian-ming

Tag::create(["标签!名"]);
// name: 标签-名
// slug: biao-qian-ming
安装说明: 安装
composer require estgroupe/laravel-taggable "5.1.*"
安装和执行迁移

config/app.phpproviders 数组中加入:

"providers" => array(
    EstGroupeTaggableProvidersTaggingServiceProvider::class,
);
php artisan vendor:publish --provider="EstGroupeTaggableProvidersTaggingServiceProvider"
php artisan migrate

请仔细阅读 config/tagging.php 文件。

创建 Tag.php

不是必须的,不过建议你创建自己项目专属的 Tag.php 文件。


修改 config/tagging.php 文件中:

    "tag_model"=>"AppModelsTag",
加入 Taggable Trait

「标签状态」标示

Taggable 能跟踪模型是否打过标签的状态:

// `no`
$article->is_tagged

// `yes`
$article->tag("Tag1");
$article->is_tagged;

// `no`
$article->unTag();
$article->is_tagged

// This is fast
$taggedArticles = Article::where("is_tagged", "yes")->get()

首先你需要修改 config/tagging.php 文件中:

"is_tagged_label_enable" => true,

然后在你的模型的数据库创建脚本里加上:

increments("id");
            ...
            // Add this line
            $table->enum("is_tagged", array("yes", "no"))->default("no");
            ...
            $table->timestamps();
        });
    }
}
「推荐标签」标示

方便你实现「推荐标签」功能,只需要把 suggest 字段标示为 true

$tag = EstGroupeTaggableModelTag::where("slug", "=", "blog")->first();
$tag->suggest = true;
$tag->save();

即可以用以下方法读取:

$suggestedTags = EstGroupeTaggableModelTag::suggested()->get();
重写 Util 类?

大部分的通用操作都发生在 Util 类,你想获取更多的定制权力,请创建自己的 Util 类,并注册服务提供者:

namespace MyProjectProviders;

use EstGroupeTaggableProvidersTaggingServiceProvider as ServiceProvider;
use EstGroupeTaggableContractsTaggingUtility;

class TaggingServiceProvider extends ServiceProvider {

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(TaggingUtility::class, function () {
            return new MyNewUtilClass;
        });
    }

}

然后在

注意 MyNewUtilClass 必须实现 EstGroupeTaggableContractsTaggingUtility 接口。

使用范例
$article = Article::with("tags")->first(); // eager load

// 获取所有标签
foreach($article->tags as $tag) {
    echo $tag->name . " with url slug of " . $tag->slug;
}

// 打标签
$article->tag("Gardening"); // attach the tag
$article->tag("Gardening, Floral"); // attach the tag
$article->tag(["Gardening", "Floral"]); // attach the tag
$article->tag("Gardening", "Floral"); // attach the tag

// 批量通过 tag ids 打标签
$article->tagWithTagIds([1,2,3]);

// 去掉标签
$article->untag("Cooking"); // remove Cooking tag
$article->untag(); // remove all tags

// 重打标签
$article->retag(["Fruit", "Fish"]); // delete current tags and save new tags
$article->retag("Fruit", "Fish");
$article->retag("Fruit, Fish");

$tagged = $article->tagged; // return Collection of rows tagged to article
$tags = $article->tags; // return Collection the actual tags (is slower than using tagged)

// 获取绑定的标签名称数组
$article->tagNames(); // get array of related tag names

// 获取打了「任意」标签的 Article 对象
Article::withAnyTag("Gardening, Cooking")->get(); // fetch articles with any tag listed
Article::withAnyTag(["Gardening","Cooking"])->get(); // different syntax, same result as above
Article::withAnyTag("Gardening","Cooking")->get(); // different syntax, same result as above

// 获取打了「全包含」标签的 Article 对象
Article::withAllTags("Gardening, Cooking")->get(); // only fetch articles with all the tags
Article::withAllTags(["Gardening", "Cooking"])->get();
Article::withAllTags("Gardening", "Cooking")->get();

EstGroupeTaggableModelTag::where("count", ">", 2)->get(); // return all tags used more than twice

Article::existingTags(); // return collection of all existing tags on any articles

如果你 创建了 Tag.php,即可使用以下标签读取功能:

// 通过 slug 获取标签
Tag::byTagSlug("biao-qian-ming")->first();

// 通过名字获取标签
Tag::byTagName("标签名")->first();

// 通过名字数组获取标签数组
Tag::byTagNames(["标签名", "标签2", "标签3"])->first();

// 通过 Tag ids 数组获取标签数组
Tag::byTagIds([1,2,3])->first();

// 通过名字数组获取 ID 数组
$ids = Tag::idsByNames(["标签名", "标签2", "标签3"])->all();
// [1,2,3]
标签事件

Taggable trait 提供以下两个事件:

EstGroupeTaggableEventsTagAdded;

EstGroupeTaggableEventsTagRemoved;

监听标签事件:

Event::listen(EstGroupeTaggableEventsTagAdded::class, function($article){
    Log::debug($article->title . " was tagged");
});
单元测试

基本用例测试请见: tests/CommonUsageTest.php

运行测试:

composer install
vendor/bin/phpunit --verbose
Thanks

Special Thanks to: Robert Conner - http://smartersoftware.net

overtrue/pinyin

etrepat/baum

Made with love by The EST Group - http://estgroupe.com/

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/21569.html

相关文章

  • 使用 Baum 嵌套集合模型来实现 Laravel 模型的无限极分类

    摘要:本文经授权转自社区使用嵌套集合模型来实现模型的无限极分类说明大家通常都是使用递归实现无限极分类,都知道递归效率很低,下面推荐一个的扩展包,快速让你的数据模型支持无限极树状层级结构,并且兼顾效率。 本文经授权转自 PHPHub 社区 使用 Baum 嵌套集合模型来实现 Laravel 模型的无限极分类 说明 大家通常都是使用递归实现无限极分类,都知道递归效率很低,下面推荐一个 Larav...

    superPershing 评论0 收藏0
  • Laravel:使用Migrations

    摘要:首先利用创建一个可迁移的数据表模板,该命令运行后会在目录下生成一个文件生成的文件包含和两个方法,其中中是包含了添加表,添加列,添加索引等等一切的描述,比较简单,就是删除表,当然里面还可以有一些其他逻辑中支持的数据表列类型,做个备注,暂时 1、首先利用artisan创建一个可迁移的数据表模板,该命令运行后会在database/migrations目录下生成一个文件 php artisan...

    waltr 评论0 收藏0
  • Laravel Telescope:优雅的应用调试工具

    摘要:文章转自视频教程优雅的应用调试工具新扩展是由和开源的应用的调试工具。计划任务列出已运行的计划任务。该封闭函数会被序列化为一个长字符串,加上他的哈希与签名如出一辙该功能将记录所有异常,并可查看具体异常情况。事件显示所有事件的列表。 文章转自:https://laravel-china.org/topics/19013视频教程:047. 优雅的应用调试工具--laravel/telesco...

    MasonEast 评论0 收藏0
  • 人人必备的10个 Laravel 4 扩展包

    摘要:更多扩展包中有丰富的扩展包来帮你完成几乎任何你想实现的功能。我们不能把所有的扩展包都整理出来,然而,这里还是列出了一些很有用的。总之,你几乎总是能够找到一个扩展包可以解决你当前的问题。 Laravel 是一个非常流行且简单易用的PHP框架,它提供了很多基础的工具(如 RESTful 路由、内置的ORM、模版等)使你能够快速的创建应用。这意味着你可以花费更少的时间来建立应用程序的模版,给...

    darkbug 评论0 收藏0
  • 13 个快速构建 Laravel 后台的扩展包

    摘要:值得一提的是扩展包不免费用于商业用途,作者用一种人类友好的方式说你使用这个扩展包就是应该去挣钱的,而不是免费的去工作这个扩展包收费美元。除了这些,还有五个没有全面的审查的扩展包。最后,还有三个优质的包选择于。 showImg(https://segmentfault.com/img/remote/1460000012312105?w=2200&h=1125); 开发者们都是懒惰的,不,...

    MiracleWong 评论0 收藏0

发表评论

0条评论

lucas

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<