sjaakp / yii2-wordcount
为 Yii2 提供单词计数行为。
Requires
- yiisoft/yii2: *
This package is auto-updated.
Last update: 2024-08-26 21:02:00 UTC
README
为 Yii2 提供单词计数行为
这是一个用于 ActiveRecords 的单词计数行为,适用于 Yii 2.0 PHP 框架。它可以统计一个或多个指定属性中的单词数。这些计数通过新的 虚拟属性 提供外部访问。
以下是 yii2-wordcount 的演示 这里。
安装
安装 yii2-wordcount 的首选方式是通过 Composer。您可以将以下内容添加到您的 composer.json
文件的 require 部分
"sjaakp/yii2-wordcount": "*"
或者运行
composer require sjaakp/yii2-wordcount "*"
您可以通过 下载 ZIP 格式的源代码 来手动安装 yii2-wordcount。
使用 WordCount
WordCount 是一个针对 Behavior 的 ActiveRecord。它有一个属性
- $attribute
string|array
我们想要计数的属性的名称。也可以是一个属性名称数组。此外,它还可以是一个具有'<attrName>' => '<countAttrName>'
元素的数组。
如果计数属性名称未在 $attribute
数组中显式设置,虚拟计数属性将自动命名为 '<attrName>_count'
。
以下是使用 WordCount 配置 ActiveRecord 的最简单方法
namespace app\models;
use yii\db\ActiveRecord;
use sjaakp\wordcount\WordCount;
class Article extends ActiveRecord
{
public static function tableName()
{
return 'article';
}
// ...
public function behaviors()
{
return [
[
'class' => WordCount::class,
'attribute' => 'bodytext'
],
// ... other behaviors ...
];
}
// ...
}
类 Article
现在将有一个新的虚拟属性,其名称为 'bodytext_count'
。它的值是一个整数,可以像查询任何其他属性一样查询它
$wordsCounted = $model->bodytext_count
使用 WordCount 配置 Activerecord 的稍微复杂的方法
// ...
class Article extends ActiveRecord
{
// ...
public function behaviors()
{
return [
[
'class' => WordCount::class,
'attribute' => [
'bodytext' => 'textcount',
'title' => 'titlecount'
]
],
// ... other behaviors ...
];
}
// ...
}
它提供了两个新的虚拟属性,名称分别为 'textcount'
和 'titlecount'
。
注意,WordCount 使用 PHP 函数 str_word_count()
。这不是统计单词的最完美方法,所以您应该将结果视为仅是良好的近似值。
总计
总计 是一个具有一个方法的辅助类
public static function count($query, $attribute)
This static function returns the total of $attribute
values in the ActiveRecords found by ActiveQuery $query
. If $attribute
is a string
, the return value will be an integer
. If $attribute
is an array of attribute names, count()
will return an array with '<attr>' => <total>
elements.
使用示例
use sjaakp\wordcount\Totals;
$totals = Totals::count(Article::find(), [ 'titlecount', 'textcount' ]);
注意,count()
也可以与非虚拟属性一起使用。然而,在这种情况下使用 ActiveQuery::sum()
将更加明智。