在PHP中完成HTTP请求后执行代码? [英] Execute code after HTTP request is complete in PHP?

查看:29
本文介绍了在PHP中完成HTTP请求后执行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 提供了一种注册关闭函数的机制:

PHP provides a mechanism to register a shutdown function:

register_shutdown_function('shutdown_func');

问题是在最近的 PHP 版本中,这个函数仍然在请求期间执行.

The problem is that in the recent versions of PHP, this function is still executed DURING the request.

我有一个平台(在 Zend Framework 中,如果这很重要),在整个请求中的任何代码段都可以注册一个条目以登录到数据库中.我没有在整个请求中使用大量单独的插入语句来减慢页面速度,而是将它们排队以在请求结束时插入.我希望能够在用户完成 HTTP 请求后执行此操作,以便记录或执行任何其他清理任务的时间长度不会影响用户感知的页面加载时间.

I have a platform (in Zend Framework if that matters) where any piece of code throughout the request can register an entry to be logged into the database. Rather than have tons of individual insert statements throughout the request, slowing the page down, I queue them up to be insert at the end of the request. I would like to be able to do this after the HTTP request is complete with the user so the length of time to log or do any other cleanup tasks doesn't affect the user's perceived load time of the page.

PHP 中是否有内置方法可以执行此操作?或者我是否需要为外部进程配置某种共享内存空间方案并通知该进程进行日志记录?

Is there a built in method in PHP to do this? Or do I need to configure some kind of shared memory space scheme with an external process and signal that process to do the logging?

推荐答案

如果您真的很关心 MySQL 的插入时间,那么您可能是在解决症状而不是原因.

If you're really concerned about the insert times of MySQL, you're probably addressing the symptoms and not the cause.

例如,如果您的 PHP/Apache 进程在用户获取其 HTML 后执行,则您的 PHP/Apache 进程仍被锁定在该请求中.由于它很忙,如果有另一个请求出现,Apache 必须派生另一个线程,为其分配更多内存,打开额外的数据库连接等.

For instance, if your PHP/Apache process is executing after the user gets their HTML, your PHP/Apache process is still locked into that request. Since it's busy, if another request comes along, Apache has to fork another thread, dedicate more memory to it, open additional database connections, etc.

如果您遇到性能问题,则需要从 PHP/Apache 执行中移除繁重的工作.如果您有很多清理任务正在进行,那么您就是在烧毁宝贵的 Apache 进程.

If you're running into performance problems, you need to remove heavy lifting from your PHP/Apache execution. If you have a lot of cleanup tasks going on, you're burning precious Apache processes.

我会考虑将您的条目记录到文件中,并让 crontab 将这些条目带外加载到您的数据库中.如果您有其他繁重的任务,请使用排队/作业处理系统进行带外工作.

I would consider logging your entries to a file and have a crontab load these into your database out of band. If you have other heavy duty tasks, use a queuing/job processing system to do the work out of band.

这篇关于在PHP中完成HTTP请求后执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆