十月CMS-覆盖模型方法

时间:2018-10-25 15:36:58

标签: octobercms octobercms-plugins octobercms-backend

我正在开发扩展Ideas Shop的插件。我的问题是我在扩展插件中已向“产品模型”中添加了一些新字段,但是该字段不适用于更新或创建某些新产品之类的操作,因为其结构是来自产品控制器的数据正在发送至Ideas \ Shop \ Facades \ Product方法saveProductData(),然后将其保存在Ideas \ Shop \ Models \ Products模型中。我的问题是如何覆盖插件扩展中的saveProductData()。

namespace Ideas\Shop\Controllers;
//class Products extends IdeasShopController

/**
 * Override create_onSave()
 */
public function create_onSave()
{
    $post = post();
    $rs = ProductFacades::saveProduct($post);
    if ($rs['rs'] != IdeasShop::SUCCESS) {
        Flash::error($rs['msg'][0]);//save flash in next refresh
    } else {
        $url = $this->handleSaveResult($rs, $post, 'create');
        return redirect($url);
    }
}

/**
 * Override update_onSave()
 */
public function update_onSave()
{
    $post = post();
    $rs = ProductFacades::saveProduct($post);
    if ($rs['rs'] != IdeasShop::SUCCESS) {
        Flash::error($rs['msg'][0]);//save flash in next refresh
    } else {
        $url = $this->handleSaveResult($rs, $post, 'update');
        return redirect($url);
    }
}

在此模型中,是我要在插件扩展中覆盖的方法...

namespace Ideas\Shop\Facades;
//class Product extends Model

public static function saveProductData($post)
{
    $id = $post['id'];
    $model = new Products();
    if ($id != 0) {//create
        $model = Products::find($id);
    }
    $product = $post['Products'];
    $model->name = $product['name'];
    $model->slug = $product['slug'];
    $model->sku = $product['sku'];
    $model->price = $product['price'];
    $model->price_promotion = $product['price_promotion'];
    $model->qty = $product['qty'];
    if ($id == 0) {
        $model->qty_order = 0;
    }
    $model->featured_image = $product['featured_image'];
    $model->product_order = $product['product_order'];
    if ($id == 0) {//create
        $model->product_type = $product['product_type'];
        $model->attribute_group_id = $product['attribute_group_id'];
    }
    $model->tax_class_id = $product['tax_class_id'];
    $model->weight = $product['weight'];
    $model->weight_id = $product['weight_id'];
    $model->status = $product['status'];
    $model->is_virtual_product = $product['is_virtual_product'];
    $model->save();
    return $model;
}

这是用于将产品中的数据保存到数据库中的模型

namespace Ideas\Shop\Models;    
class Products extends Model
    {
      ...
    }

1 个答案:

答案 0 :(得分:1)

嗯,您无法覆盖其方法,但是可以监听其before save事件,然后分配您添加的其他字段

\Ideas\Shop\Models\Products::extend(function($model) {

    $model->bindEvent('model.beforeSave', function() use ($model) {

        // you can receive data from post() may be and assign
        $model->my_new_field = 'some data';
    });
});
  

它将在保存之前设置字段数据,因此在保存模型时会将数据持久保存到数据库中。

如果您需要扩展更多内容,可以使用以下引用:https://octobercms.com/docs/database/model#extending-models

如有疑问,请发表评论。