letharion / reloaded

此包最新版本(dev-master)没有可用的许可信息。

帮助管理运行时代码更新。

dev-master 2014-09-15 19:37 UTC

This package is not auto-updated.

Last update: 2024-09-28 15:54:46 UTC


README

运行时代码更新的工具。适用于持续运行的PHP应用程序。

使用 React 服务器的示例

<?php

require 'vendor/autoload.php';

use Letharion\Reloaded\Reloaders\Stat;
use Letharion\Reloaded\Validators\NumArgs;

// Create a new loader that decides when to reload code based on the files
// last modification time.
// Tell it to load the file 'example.php', and pass it a validator that
// requires the loaded function to have a single parameter. See validators
// below
$stat = new Stat('example.php', new NumArgs(0));

$app = function ($request, $response) use ($stat) {
  // Get the function we want. On most iterations this will just return
  // a reference to a previously loaded function, and will have negliable
  // performance cost. However, if the file has been modified since it was
  // last loaded, it will now be reloaded, and the runtime behavior has
  // been changed.
  $func = $stat->getFunction();

  $text = $func();

  $headers = array('Content-Type' => 'application/json');

  $response->writeHead(200, $headers);
  $response->end($text);
};

$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket);

$http->on('request', $app);

$socket->listen(1337);
$loop->run();

上面的代码将运行一个HTTP服务器,对所有请求响应$func函数返回的内容。如果文件'example.php'自上次加载以来已更新,它还会重新加载该文件。因此,可以轻松修改应用程序的运行时行为,而无需重新启动它。

验证器

Stat()的第二个参数是一个验证器。验证器可以用来确保只加载'有效'的代码作为替换。如果验证失败,将保持之前使用的函数。这可以保护应用程序即使在意外推送了新坏代码的情况下也不会崩溃。

示例验证器只是简单地测试新函数是否有正确的参数数量,但可以像需要的那样复杂。