ds1379551 2013-12-05 06:56
浏览 41
已采纳

从db调用匿名函数

I use Yii in my project and want realize event model with callbacks. I made "Event" model in MySQL and want store anonymous functions in many fields, for example,

**Event model in Yii**
id - int
name - varchar(255)
beforeEvent - text

In "afterEvent" field stored function:

 function(){echo 'afterEvent #1';}

Then i fetch all events and try call "afterEvent" function:

$events     = Event::model()->findAll();
foreach ($events as $event)
{
   $event->beforeEvent();                            
}

As i haven't that method in model Event, i made proxy method

public function beforeEvent() { call_user_func($this->beforeEvent); }

Problem in error:

call_user_func() expects parameter 1 to be a valid callback, function 'function(){ echo 'afterEvent of event #1 done'; }' not found or invalid function name


Found 1 solution: in proxy-method beforeEvent() use create_function function like this:

public function beforeEvent(array $params){
$callback = create_function('$params', $this->beforeEvent);
$callback($params);
}

but in manual said:

This function internally performs an eval() and as such has the same security issues as eval(). Additionally it has bad performance and memory usage characteristics. If you are using PHP 5.3.0 or newer a native anonymous function should be used instead.

and we khow that eval is evil. How can i use anonymous function in this situation?

  • 写回答

2条回答 默认 最新

  • drn34916 2013-12-05 08:41
    关注

    Don't store code in the database. There's only a finite number of things that can happen after an event, and the functions for those are somewhere in your code base to begin with. There's no need to copy them into the database and then try to evaluate them from there. Just store an identifier for what you want to happen at a certain event (e.g. sendEmail), then call the appropriate function for that action in your code.

    This is also a lot saner with regards to being able to refactor your code. Imagine you have to rewrite something that would break a million callback functions stored in your database... not a fun situation. The data is your asset, the code is just what makes this asset accessible. As a rule of thumb, always keep in the back of your head "What if I strike gold with this project, suddenly need to scale to 100x the size and I hire an agency to rewrite everything in more scalable platform X over night, could I simply continue using the same data?" Therefore the data should be platform agnostic. Storing executable code in the database isn't.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致
  • ¥15 禅道二次开发编辑版本,上传不了发行包