php通用过滤,php – Lithium通用模型过滤器

我目前正在开发一个Lithium应用程序,它需要在调用save()之前向对象添加各种内容.

理想情况下,我可以编写一个过滤器来应用于Model类(其他模型扩展的基本模型),如下所示:

Model::applyFilter('save', function($self, $params, $chain) {

// Logic here

});

这可能吗?如果是这样,它应该是一个自举文件?

解决方法:

如果我没有误解你所说的内容,你想要在保存之前自动为对象添加“已创建”或“已修改”的值.

我就是这样做的.

来自我的extensions / data / Model.php

namespace app\extensions\data;

use lithium\security\Password;

class Model extends \lithium\data\Model {

public static function __init() {

parent::__init();

// {{{ Filters

static::applyFilter('save', function($self, $params, $chain) {

$date = date('Y-m-d H:i:s', time());

$schema = $self::schema();

//do these things only if they don't exist (i.e. on creation of object)

if (!$params['entity']->exists()) {

//hash password

if (isset($params['data']['password'])) {

$params['data']['password'] = Password::hash($params['data']['password']);

}

//if 'created' doesn't already exist and is defined in the schema...

if (empty($params['date']['created']) && array_key_exists('created', $schema)) {

$params['data']['created'] = $date;

}

}

if (array_key_exists('modified', $schema)) {

$params['data']['modified'] = $date;

}

return $chain->next($self, $params, $chain);

});

// }}}

}

}

?>

我也有一些密码哈希.您可以删除它而不影响任何功能.

标签:php,filter,aop,lithium

来源: https://codeday.me/bug/20190723/1513578.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值