gielfeldt/shutdownhandler

关闭处理器。

1.2.0 2015-09-20 19:24 UTC

This package is not auto-updated.

Last update: 2024-09-14 17:32:08 UTC


README

Build Status Test Coverage Scrutinizer Code Quality Code Climate

Latest Stable Version Latest Unstable Version Dependency Status License Total Downloads

Documentation Status Documentation Status

安装

要在项目中使用Composer安装ShutdownHandler库,首先将以下内容添加到您的composer.json配置文件中。

{
    "require": {
        "gielfeldt/shutdownhandler": "~1.0"
    }
}

然后运行Composer的安装或更新命令以完成安装。请访问Composer主页以获取有关如何使用Composer的更多信息。

关闭处理器

这个关闭处理器类允许您创建高级关闭处理器,创建后可以对其进行操作。

动机

  1. 在致命错误的情况下,不会运行析构函数。在我特定的情况下,我需要一个在自我清理方面健壮的锁类。请参阅下面的“示例 2”或examples/fatal.php以获取示例。

  2. PHP关闭处理器在注册后无法进行操作(注销、执行等)。

示例 1 - 使用关闭处理器

namespace Gielfeldt\ShutdownHandler\Example;

require 'vendor/autoload.php';

use Gielfeldt\ShutdownHandler\ShutdownHandler;

/**
 * Simple shutdown handler callback.
 *
 * @param string $message
 *   Message to display during shutdown.
 */
function myshutdownhandler($message = '')
{
    echo "Goodbye $message\n";
}

// Register shutdown handler to be run during PHP shutdown phase.
$handler = new ShutdownHandler('\Gielfeldt\ShutdownHandler\Example\myshutdownhandler', array('cruel world'));

echo "Hello world\n";

// Register shutdown handler.
$handler2 = new ShutdownHandler('\Gielfeldt\ShutdownHandler\Example\myshutdownhandler', array('for now'));

// Don't wait for shutdown phase, just run now.
$handler2->run();

示例 2 - 确保对象销毁

namespace Gielfeldt\ShutdownHandler\Example;

require 'vendor/autoload.php';

use Gielfeldt\ShutdownHandler\ShutdownHandler;

/**
 * Test class with destructor via Gielfeldt\ShutdownHandler\ShutdownHandler.
 */
class MyClass
{
    /**
     * Reference to the shutdown handler object.
     * @var ShutdownHandler
     */
    protected $shutdown;

    /**
     * Constructor.
     *
     * @param string $message
     *   Message to display during destruction.
     */
    public function __construct($message = '')
    {
        // Register our shutdown handler.
        $this->shutdown = new ShutdownHandler(array(get_class($this), 'shutdown'), array($message));
    }

    /**
     * Run our shutdown handler upon object destruction.
     */
    public function __destruct()
    {
        $this->shutdown->run();
    }

    /**
     * Our shutdown handler.
     *
     * @param string $message
     *   The message to display.
     */
    public static function shutdown($message = '')
    {
        echo "Destroy $message\n";
    }
}

// Instantiate object.
$obj = new MyClass("world");

// Destroy object. The object's shutdown handler will be run.
unset($obj);

// Instantiate new object.
$obj = new MyClass("universe");

// Object's shutdown handler will be run on object's destruction or when PHP's
// shutdown handlers are executed. Whichever comes first.

有关更多示例,请参阅examples/文件夹。

功能

  • 注销关闭处理器
  • 提前运行关闭处理器
  • 通过确保通过PHP关闭处理器进行销毁来改进对象析构函数
  • 键控关闭处理器,允许轻松去重多个关闭处理器

注意事项

  1. 很多。