dan-da/strictmode-php

此包的最新版本(v1.0.2)没有可用的许可证信息。

v1.0.2 2023-11-05 17:47 UTC

This package is auto-updated.

Last update: 2024-09-05 19:45:08 UTC


README

这是一个小巧的PHP包含文件,可以使PHP代码更加严格,并尽早捕获问题。

此库捕获所有PHP通知、警告和错误,并将它们转换为PHP异常。

它还捕获所有未捕获的异常并打印堆栈跟踪。它还可以为未捕获的异常发送电子邮件警报。

结果是,在开发早期就能捕获到小问题,并迫使开发者编写更干净的代码。

电子邮件警报对于生产环境很有用,可以通知站点管理员任何问题。

strictmode.php是一个单文件,可以使用require_once包含,或者在使用composer时通过自动加载包含。

让我们看一个例子。

应用代码

这使用require_once(),下面是自动加载示例。

<?php
require_once( __DIR__ . '/../strictmode.php');
define( 'strictmode\ALERTS_MAILTO', 'yourmail@yourdomain.com' );
...

echo HELLO;   // this will generate a PHP notice.

输出

Uncaught Exception. code: 8, message: Use of undefined constant HELLO - assumed 'HELLO'
/home/danda/dev/strictmode-php/t.php : 7

Stack Trace:
#0 /home/danda/dev/strictmode-php/t.php(7): strictmode\_global_error_handler(8, 'Use of undefine...', '/home/danda/dev...', 7, Array)
#1 {main}

INFO: alert sent to yourmail@yourdomain.com


Now exiting.  Please report this problem to the software author

为了比较,以下是正常PHP输出(没有strictmode.php)

PHP Notice:  Use of undefined constant HELLO - assumed 'HELLO' in /home/danda/dev/strictmode-php/t.php on line 7
HELLO

通过composer自动加载

<?php
require_once __DIR__  . '/../vendor/autoload.php';
define( 'strictmode\ALERTS_MAILTO', 'yourmail@yourdomain.com' );
\strictmode\initializer::init();

// your app code...

配置电子邮件警报

设置警报地址

define( 'strictmode\ALERTS_MAILTO', 'yourmail@yourdomain.com' );

如果没有设置ALERTS_MAILTO,则禁用警告

define( 'strictmode\ALERTS_DISABLE', 1 );

安装和运行

使用composer.json中的composer require将strictmode-php安装到您的项目中,例如

    $ cd yourproject
    $ composer require dan-da/strictmode-php

然后运行composer install。

待办事项

  • 添加更多测试用例