2017 © Pedro Peláez
 

yii2-extension tags-behavior-yii2

Tags Behavior for Yii2

image

rkit/tags-behavior-yii2

Tags Behavior for Yii2

  • Sunday, July 22, 2018
  • by rkit
  • Repository
  • 1 Watchers
  • 0 Stars
  • 0 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 2 Versions
  • 0 % Grown

The README.md

Tags Behavior for Yii2

Build Status Scrutinizer Code Quality, (*1)

Flexible yii2 behavior for tags., (*2)

Requirements

PHP 7, (*3)

Installation

composer require rkit/tags-behavior-yii2

Configuration

For example, we have a Post model and we want to add tags.
Let's do it., (*4)

  1. Add tag and post_to_tag tables and a Tag model for the tags
$this->createTable('{{%tag}}', [
    'id' => $this->primaryKey(),
    'name' => $this->string()->notNull()->unique(),
    'frequency' => $this->integer()->notNull()->defaultValue(0),
]);

$this->createTable('{{%post_to_tag}}', [
    'post_id' => $this->integer()->notNull()->defaultValue(0),
    'tag_id' => $this->integer()->notNull()->defaultValue(0),
]);

$this->addPrimaryKey('', '{{%post_to_tag}}', ['post_id', 'tag_id']);
  1. Add a TagsBehavior behavior to the Post model
public function behaviors()
{
    return [
        'tagsBehavior' => [
            'class' => 'rkit\tags\behavior\TagsBehavior',
            'relation' => 'tags',
            'tagAttribute' => 'name',
            'tagFrequencyAttribute' => 'frequency', // or false
            'findTag' => function ($value) {
                return Tag::find()->where([$this->tagAttribute => $value])->one();
            },
            'createTag' => function ($value) {
                $tag = new Tag();
                $tag->{$this->tagAttribute} = $value;
                return $tag;
            },
        ],
    ];
}
  1. Add a tags relation (see relation option in the behavior)
/**
 * @return \yii\db\ActiveQuery
 */
public function getTags()
{
    return $this
        ->hasMany(Tag::class, ['id' => 'tag_id'])
        ->viaTable('{{%post_to_tag}}', ['post_id' => 'id']);
}

Usage

Add tags

$model = new Post();
$model->setTagValues(['example1', 'example2']);
$model->save();

Get tags

$post = Post::find()->with('tags')->where(['id' => $id])->one();
$post->getTagValues();

Remove tags

$model = new Post();
$model->setTagValues([]);
$model->save();

Tests

Coding Standard

The Versions

22/07 2018

dev-master

9999999-dev https://github.com/rkit/tags-behavior-yii2

Tags Behavior for Yii2

  Sources   Download

MIT

The Requires

 

The Development Requires

by Igor Romanov

extension yii2 behavior tags

16/07 2018

1.0.0

1.0.0.0 https://github.com/rkit/tags-behavior-yii2

Tags Behavior for Yii2

  Sources   Download

MIT

The Requires

 

The Development Requires

by Igor Romanov

extension yii2 behavior tags