kenjebaev/yii2-compare

为 Yii2 比较功能

安装次数: 27

依赖关系: 0

建议者: 0

安全: 0

星标: 1

关注者: 1

分支: 0

开放问题: 0

类型:yii2-extension

dev-master 2022-01-30 07:53 UTC

This package is auto-updated.

Last update: 2024-09-08 02:52:59 UTC


README

此扩展为 Yii 2.0 框架添加比较功能

安装

安装此扩展的首选方式是通过 Composer

运行以下命令之一:

php composer.phar require kenjebaev/yii2-compare"*"

或者添加以下内容到你的 composer.json 文件的 require 部分。

kenjebaev/yii2-compare: "*"

require

配置

配置 compare 组件(默认值如下所示)

return [
    //...
    'components' => [
        //...
        'compare' => [
            'class' => 'kenjebaev\compare\Compare',
            'storageClass' => 'kenjebaev\compare\storage\SessionStorage',
            'params' => [
                'key' => 'compare',
                'expire' => 604800,
                'productClass' => 'app\model\Product',
                'productFieldId' => 'id',
            ],
        ],
    ]
    //...
];

除了 kenjebaev\compare\storage\SessionStorage,还有 kenjebaev\compare\storage\CookieStoragekenjebaev\compare\storage\DbSessionStorage。你可以创建自己的存储,需要实现 kenjebaev\compare\storage\StorageInterface 接口。

DbSessionStorage 使用 SessionStorage 为未经授权的用户,并使用数据库为授权用户。

如果你使用 kenjebaev\compare\storage\DbSessionStorage 作为 storageClass,则需要应用以下迁移

php yii migrate --migrationPath=@vendor/kenjebaev/yii2-compare/migrations

设置 params 数组

  • key - 对于 Session 和 Cookie。

  • expire - Cookie 生命周期。

  • productClass - 产品类是一个 ActiveRecord 模型。

  • productFieldId - 产品模型 id 字段的名称。

用法

你可以在应用程序的任何地方使用 Yii::$app->compare 来获取比较组件。

使用比较

// Product is an AR model
$product = Product::findOne(1);

// Get component of the compare
$compare = \Yii::$app->compare;

// Add an item to the compare
$compare->add($product);

// Removes an items from the compare
$compare->remove($product->id);

// Removes all items from the compare
$compare->clear();

// Get all items from the compare
$compare->getItems();

// Get an item from the compare
$compare->getItem($product->id);

// Get ids array all items from the compare
$compare->getItemIds();

使用比较项

// Product is an AR model
$product = Product::findOne(1);

// Get component of the compare
$compare = \Yii::$app->compare;

// Get an item from the compare
$item = $compare->getItem($product->id);

// Get the id of the item
$item->getId();

// Get the product, AR model
$item->getProduct();

通过使用 getProduct() 方法,你可以访问产品的所有属性和方法。

$product = $item->getProduct();

echo $product->name;