PSR是PHP通用性框架小组 (PHP Framework Interop Group) 制定的PHP代码编写格式规范,是PHP开发的事实标准。
截止到目前(2015年2月),正式发布过的PHP规范共有5个:
那么使用、遵循PSR标准有什么必要和好处呢?统一的编码风格,可以让我们轻松愉悦地阅读他人的代码,以及编写让他人的代码。
就PSR规范本身来说,个人觉得是非常优秀、简洁的实践结晶。遵循这些标准,除了能使我们的代码更加可读之外,还能让我们的程序更加健壮,更能提高开发者的个人素养。
下面罗列一下PSR 1 ~ PSR 4的主要内容(已废弃的PSR 0不再介绍):
<?php
// 副作用:修改了ini配置
ini_set('error_reporting', E_ALL);
// 副作用:载入了文件
include "file.php";
// 副作用:产生了输出
echo "<html>\n";
// 声明
function foo()
{
// 函数体
}
提倡的例子,仅包含声明:
<?php
// 声明
function foo()
{
// 函数体
}
// 条件式声明不算做是副作用
if (! function_exists('bar')) {
function bar()
{
// 函数体
}
}
<?php
namespace Vendor\Model;
class StudlyCaps
{
// 代码
}
<?php
namespace Vendor\Model;
class Foo
{
const VERSION = '1.0';
const DATE_APPROVED = '2012-06-01';
}
if ($a === true) {
echo 'yes';
} else {
echo 'no';
}
符合PSR-3推荐规范的PHP日志记录器组件,必须包含一个实现Psr\Log\LoggerInterface接口的PHP类。要实现九个方法:
<?php
namespace Psr\Log;
interface LoggerInterface
{
public function emergency($message, array $content = array());
public function alert($message, array $content = array());
public function critical($message, array $content = array());
public function warning($message, array $content = array());
public function notice($message, array $content = array());
public function info($message, array $content = array());
public function debug($message, $array $content = array());
public function log($level, $message, array $content = array());
}
<?php namespace Psr\Log; class LogLevel { const EMERGENCY = 'emergency'; const ALERT = 'alert'; const CRITICAL = 'critical'; const ERROR = 'error'; const WARNING = 'warning'; const NOTICE = 'notice'; const INFO = 'info'; const DEBUG = 'debug'; }
参考资料: