arjunacoding/bedigas

Bedigas 是一个快速、简单、可扩展的 PHP 框架。Bedigas 允许您快速轻松地构建 RESTful 网络应用程序。

dev-master 2019-11-24 00:33 UTC

This package is auto-updated.

Last update: 2024-09-24 11:23:43 UTC


README

Bedigas 是一个快速、简单、可扩展的 PHP 框架。Bedigas 允许您快速轻松地构建 RESTful 网络应用程序。

require 'bedigas/Bedigas.php';

Bedigas::route('/', function(){
    echo 'hello world!';
});

Bedigas::start();

了解更多

要求

Bedigas 需要 PHP 5.3 或更高版本。

许可

Bedigas 在 MIT 许可下发布。

安装

1. 下载文件。

如果您使用 Composer,可以运行以下命令

composer require arjunacoding/bedigas

或者您可以直接 下载 并将它们解压到您的网络目录中。

2. 配置您的 web 服务器。

对于 Apache,使用以下内容编辑您的 .htaccess 文件

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

注意:如果您需要在子目录中使用 bedigas,请在 RewriteEngine On 后添加行 RewriteBase /subdir/

对于 Nginx,将以下内容添加到您的服务器声明中

server {
    location / {
        try_files $uri $uri/ /index.php;
    }
}

3. 创建您的 index.php 文件。

首先包含框架。

require 'bedigas/Bedigas.php';

如果您使用 Composer,运行自动加载器。

require 'vendor/autoload.php';

然后定义一个路由并将一个函数分配给处理请求。

Bedigas::route('/', function(){
    echo 'hello world!';
});

最后,启动框架。

Bedigas::start();

路由

Bedigas 中的路由是通过匹配 URL 模式与回调函数来实现的。

Bedigas::route('/', function(){
    echo 'hello world!';
});

回调可以是任何可调用的对象。因此,您可以使用常规函数

function hello(){
    echo 'hello world!';
}

Bedigas::route('/', 'hello');

或者类方法

class Greeting {
    public static function hello() {
        echo 'hello world!';
    }
}

Bedigas::route('/', array('Greeting', 'hello'));

或者对象方法

class Greeting
{
    public function __construct() {
        $this->name = 'John Doe';
    }

    public function hello() {
        echo "Hello, {$this->name}!";
    }
}

$greeting = new Greeting();

Bedigas::route('/', array($greeting, 'hello')); 

路由按照定义的顺序进行匹配。第一个匹配请求的路由将被调用。

方法路由

默认情况下,路由模式与所有请求方法匹配。您可以通过在 URL 前放置标识符来响应特定方法。

Bedigas::route('GET /', function(){
    echo 'I received a GET request.';
});

Bedigas::route('POST /', function(){
    echo 'I received a POST request.';
});

您还可以使用 | 分隔符将多个方法映射到单个回调

Bedigas::route('GET|POST /', function(){
    echo 'I received either a GET or a POST request.';
});

正则表达式

您可以在路由中使用正则表达式

Bedigas::route('/user/[0-9]+', function(){
    // This will match /user/1234
});

命名参数

您可以在路由中指定命名参数,这些参数将被传递到回调函数中。

Bedigas::route('/@name/@id', function($name, $id){
    echo "hello, $name ($id)!";
});

您还可以通过使用 : 分隔符将正则表达式包含在命名参数中

Bedigas::route('/@name/@id:[0-9]{3}', function($name, $id){
    // This will match /bob/123
    // But will not match /bob/12345
});

可选参数

您可以通过在括号中包裹段来指定可选的命名参数以进行匹配。

Bedigas::route('/blog(/@year(/@month(/@day)))', function($year, $month, $day){
    // This will match the following URLS:
    // /blog/2012/12/10
    // /blog/2012/12
    // /blog/2012
    // /blog
});

未匹配的任何可选参数都将作为 NULL 传递。

通配符

匹配仅发生在单个 URL 段上。如果您想匹配多个段,可以使用 * 通配符。

Bedigas::route('/blog/*', function(){
    // This will match /blog/2000/02/01
});

要将所有请求路由到单个回调,您可以这样做

Bedigas::route('*', function(){
    // Do something
});

传递

您可以通过从回调函数中返回 true 将执行权传递给下一个匹配的路由。

Bedigas::route('/user/@name', function($name){
    // Check some condition
    if ($name != "Bob") {
        // Continue to next route
        return true;
    }
});

Bedigas::route('/user/*', function(){
    // This will get called
});

路由信息

如果您想检查匹配的路由信息,可以通过将 true 作为路由方法的第三个参数传递来请求将路由对象传递到您的回调。路由对象将始终是传递到最后一个参数的回调函数。

Bedigas::route('/', function($route){
    // Array of HTTP methods matched against
    $route->methods;

    // Array of named parameters
    $route->params;

    // Matching regular expression
    $route->regex;

    // Contains the contents of any '*' used in the URL pattern
    $route->splat;
}, true);

扩展

Bedigas 被设计为可扩展的框架。该框架提供了一组默认方法和组件,但它允许您映射自己的方法,注册自己的类,甚至覆盖现有的类和方法。

映射方法

要映射自己的自定义方法,您使用 map 函数

// Map your method
Bedigas::map('hello', function($name){
    echo "hello $name!";
});

// Call your custom method
Bedigas::hello('Bob');

注册类

要注册您自己的类,您使用 register 函数

// Register your class
Bedigas::register('user', 'User');

// Get an instance of your class
$user = Bedigas::user();

register 方法还允许您将参数传递给类构造函数。因此,当您加载自定义类时,它将预先初始化。您可以通过传递额外的数组来定义构造函数参数。以下是一个加载数据库连接的示例

// Register class with constructor parameters
Bedigas::register('db', 'PDO', array('mysql:host=localhost;dbname=test','user','pass'));

// Get an instance of your class
// This will create an object with the defined parameters
//
//     new PDO('mysql:host=localhost;dbname=test','user','pass');
//
$db = Bedigas::db();

如果您传递额外的回调参数,它将在类构造后立即执行。这允许您为新的对象执行任何设置程序。回调函数接受一个参数,即新对象的实例。

// The callback will be passed the object that was constructed
Bedigas::register('db', 'PDO', array('mysql:host=localhost;dbname=test','user','pass'), function($db){
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
});

默认情况下,每次您加载类时,您都会得到一个共享实例。要获取类的全新实例,只需将 false 作为参数传递

// Shared instance of the class
$shared = Bedigas::db();

// New instance of the class
$new = Bedigas::db(false);

请注意,映射方法具有优先级高于注册类。如果您使用相同的名称声明两者,则只会调用映射方法。

重写

Bedigas 允许您覆盖其默认功能以满足您自己的需求,而无需修改任何代码。

例如,当 Bedigas 无法将 URL 匹配到路由时,它将调用 notFound 方法,该方法发送通用的 HTTP 404 响应。您可以通过使用 map 方法来覆盖此行为

Bedigas::map('notFound', function(){
    // Display custom 404 page
    include 'errors/404.html';
});

Bedigas 还允许您替换框架的核心组件。例如,您可以替换默认的 Router 类为您的自定义类

// Register your custom class
Bedigas::register('router', 'MyRouter');

// When Bedigas loads the Router instance, it will load your class
$myrouter = Bedigas::router();

然而,框架方法如 mapregister 不能被重写。如果您尝试这样做,将会得到错误。

过滤

Bedigas 允许您在方法被调用前后对其进行过滤。没有预定义的钩子需要记住。您可以过滤任何默认框架方法以及您已映射的任何自定义方法。

一个过滤函数看起来像这样

function(&$params, &$output) {
    // Filter code
}

使用传入的变量,您可以操作输入参数和/或输出。

您可以通过这样做来使过滤器在方法之前运行

Bedigas::before('start', function(&$params, &$output){
    // Do something
});

您可以通过这样做来使过滤器在方法之后运行

Bedigas::after('start', function(&$params, &$output){
    // Do something
});

您可以将任意数量的过滤器添加到任何方法中。它们将按照声明的顺序调用。

以下是一个过滤过程的示例

// Map a custom method
Bedigas::map('hello', function($name){
    return "Hello, $name!";
});

// Add a before filter
Bedigas::before('hello', function(&$params, &$output){
    // Manipulate the parameter
    $params[0] = 'Fred';
});

// Add an after filter
Bedigas::after('hello', function(&$params, &$output){
    // Manipulate the output
    $output .= " Have a nice day!";
});

// Invoke the custom method
echo Bedigas::hello('Bob');

这将显示

Hello Fred! Have a nice day!

如果您定义了多个过滤器,您可以通过在任意一个过滤函数中返回 false 来断开链。

Bedigas::before('start', function(&$params, &$output){
    echo 'one';
});

Bedigas::before('start', function(&$params, &$output){
    echo 'two';

    // This will end the chain
    return false;
});

// This will not get called
Bedigas::before('start', function(&$params, &$output){
    echo 'three';
});

请注意,核心方法如 mapregister 不能被过滤,因为它们是直接调用而不是动态调用的。

变量

Bedigas 允许您保存变量,以便在应用程序的任何地方使用。

// Save your variable
Bedigas::set('id', 123);

// Elsewhere in your application
$id = Bedigas::get('id');

要检查变量是否已设置,您可以这样做

if (Bedigas::has('id')) {
     // Do something
}

您可以通过这样做来清除变量

// Clears the id variable
Bedigas::clear('id');

// Clears all variables
Bedigas::clear();

Bedigas 也使用变量进行配置。

Bedigas::set('bedigas.log_errors', true);

视图

Bedigas 默认提供一些基本的模板功能。要显示视图模板,请使用带有模板文件名称和可选模板数据的 render 方法

Bedigas::render('hello.php', array('name' => 'Bob'));

您传入的模板数据将自动注入到模板中,并可以像局部变量一样引用。模板文件只是 PHP 文件。如果 hello.php 模板文件的 内容是

Hello, '<?php echo $name; ?>'!

输出将是

Hello, Bob!

您也可以使用 set 方法手动设置视图变量

Bedigas::view()->set('name', 'Bob');

变量 name 现在在所有视图中都是可用的。因此,您可以这样做

Bedigas::render('hello');

请注意,在指定 render 方法中的模板名称时,您可以省略 .php 扩展名。

默认情况下,Bedigas 将在 views 目录中查找模板文件。您可以通过设置以下配置来为模板设置不同的路径

Bedigas::set('bedigas.views.path', '/path/to/views');

布局

网站通常使用单个布局模板文件,其中包含可交换的内容。要渲染用于布局的内容,您可以在render方法中传递一个可选参数。

Bedigas::render('header', array('heading' => 'Hello'), 'header_content');
Bedigas::render('body', array('body' => 'World'), 'body_content');

您的视图将保存名为header_contentbody_content的变量。然后,您可以通过以下方式渲染布局:

Bedigas::render('layout', array('title' => 'Home Page'));

如果模板文件如下所示:

header.php:

<h1><?php echo $heading; ?></h1>

body.php:

<div><?php echo $body; ?></div>

layout.php:

<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $header_content; ?>
<?php echo $body_content; ?>
</body>
</html>

输出将是

<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Hello</h1>
<div>World</div>
</body>
</html>

自定义视图

Bedigas允许您通过注册自己的视图类来简单替换默认视图引擎。以下是如何为您的视图使用Smarty模板引擎的方法

// Load Smarty library
require './Smarty/libs/Smarty.class.php';

// Register Smarty as the view class
// Also pass a callback function to configure Smarty on load
Bedigas::register('view', 'Smarty', array(), function($smarty){
    $smarty->template_dir = './templates/';
    $smarty->compile_dir = './templates_c/';
    $smarty->config_dir = './config/';
    $smarty->cache_dir = './cache/';
});

// Assign template data
Bedigas::view()->assign('name', 'Bob');

// Display the template
Bedigas::view()->display('hello.tpl');

为了完整起见,您还应重写Bedigas的默认渲染方法

Bedigas::map('render', function($template, $data){
    Bedigas::view()->assign($data);
    Bedigas::view()->display($template);
});

错误处理

错误和异常

Bedigas会捕获所有错误和异常,并将它们传递给error方法。默认行为是发送一个通用的HTTP 500 内部服务器错误响应,其中包含一些错误信息。

您可以为此根据自己的需求重写此行为

Bedigas::map('error', function(Exception $ex){
    // Handle error
    echo $ex->getTraceAsString();
});

默认情况下,错误不会记录到Web服务器。您可以通过更改配置来启用此功能

Bedigas::set('bedigas.log_errors', true);

未找到

当URL无法找到时,Bedigas会调用notFound方法。默认行为是发送一个简单的HTTP 404 未找到响应。

您可以为此根据自己的需求重写此行为

Bedigas::map('notFound', function(){
    // Handle not found
});

重定向

您可以通过使用redirect方法并传递一个新URL来重定向当前请求

Bedigas::redirect('/new/location');

默认情况下,Bedigas发送HTTP 303状态码。您可以选择设置一个自定义代码

Bedigas::redirect('/new/location', 401);

请求

Bedigas将HTTP请求封装到一个单独的对象中,可以通过以下方式访问

$request = Bedigas::request();

请求对象提供以下属性

url - The URL being requested
base - The parent subdirectory of the URL
method - The request method (GET, POST, PUT, DELETE)
referrer - The referrer URL
ip - IP address of the client
ajax - Whether the request is an AJAX request
scheme - The server protocol (http, https)
user_agent - Browser information
type - The content type
length - The content length
query - Query string parameters
data - Post data or JSON data
cookies - Cookie data
files - Uploaded files
secure - Whether the connection is secure
accept - HTTP accept parameters
proxy_ip - Proxy IP address of the client
host - The request host name

您可以将querydatacookiesfiles属性作为数组或对象访问。

因此,要获取查询字符串参数,您可以这样做

$id = Bedigas::request()->query['id'];

或者您也可以这样做

$id = Bedigas::request()->query->id;

原始请求体

要获取原始HTTP请求体,例如处理PUT请求时,您可以这样做

$body = Bedigas::request()->getBody();

JSON输入

如果您发送一个类型为application/json并且数据为{"id": 123}的请求,它将可通过data属性访问

$id = Bedigas::request()->data->id;

HTTP缓存

Bedigas提供了内置的HTTP级缓存支持。如果满足缓存条件,Bedigas将返回一个HTTP 304 Not Modified响应。下次客户端请求同一资源时,他们将被提示使用本地缓存的版本。

Last-Modified

您可以使用lastModified方法并传递一个UNIX时间戳来设置页面最后修改的日期和时间。客户端将继续使用他们的缓存,直到最后修改值发生变化。

Bedigas::route('/news', function(){
    Bedigas::lastModified(1234567890);
    echo 'This content will be cached.';
});

ETag

ETag缓存类似于Last-Modified,但您可以指定任何您想要的资源ID

Bedigas::route('/news', function(){
    Bedigas::etag('my-unique-id');
    echo 'This content will be cached.';
});

请注意,调用lastModifiedetag都会设置和检查缓存值。如果在请求之间缓存值相同,Bedigas将立即发送一个HTTP 304响应并停止处理。

停止

您可以在任何时刻通过调用halt方法来停止框架

Bedigas::halt();

您还可以指定一个可选的HTTP状态码和消息

Bedigas::halt(200, 'Be right back...');

调用halt将丢弃到该点为止的所有响应内容。如果您想停止框架并输出当前的响应,请使用stop方法

Bedigas::stop();

JSON

Bedigas提供了发送JSON和JSONP响应的支持。要发送JSON响应,您将一些要JSON编码的数据传递给

Bedigas::json(array('id' => 123));

对于JSONP请求,您可以可选地传递用于定义回调函数的查询参数名称。

Bedigas::jsonp(array('id' => 123), 'q');

因此,当使用?q=my_func进行GET请求时,您应该接收到输出。

my_func({"id":123});

如果您没有传递查询参数名称,它将默认为jsonp

配置

您可以通过set方法设置配置值来自定义Bedigas的一些行为。

Bedigas::set('bedigas.log_errors', true);

以下是一个所有可用配置设置的列表。

bedigas.base_url - Override the base url of the request. (default: null)
bedigas.case_sensitive - Case sensitive matching for URLs. (default: false)
bedigas.handle_errors - Allow Bedigas to handle all errors internally. (default: true)
bedigas.log_errors - Log errors to the web server's error log file. (default: false)
bedigas.views.path - Directory containing view template files. (default: ./views)
bedigas.views.extension - View template file extension. (default: .php)

框架方法

Bedigas旨在易于使用和理解。以下是框架的完整方法集合。它包括核心方法,这些是常规静态方法,以及可扩展方法,这些是映射方法,可以进行过滤或覆盖。

核心方法

Bedigas::map($name, $callback) // Creates a custom framework method.
Bedigas::register($name, $class, [$params], [$callback]) // Registers a class to a framework method.
Bedigas::before($name, $callback) // Adds a filter before a framework method.
Bedigas::after($name, $callback) // Adds a filter after a framework method.
Bedigas::path($path) // Adds a path for autoloading classes.
Bedigas::get($key) // Gets a variable.
Bedigas::set($key, $value) // Sets a variable.
Bedigas::has($key) // Checks if a variable is set.
Bedigas::clear([$key]) // Clears a variable.
Bedigas::init() // Initializes the framework to its default settings.
Bedigas::app() // Gets the application object instance

可扩展方法

Bedigas::start() // Starts the framework.
Bedigas::stop() // Stops the framework and sends a response.
Bedigas::halt([$code], [$message]) // Stop the framework with an optional status code and message.
Bedigas::route($pattern, $callback) // Maps a URL pattern to a callback.
Bedigas::redirect($url, [$code]) // Redirects to another URL.
Bedigas::render($file, [$data], [$key]) // Renders a template file.
Bedigas::error($exception) // Sends an HTTP 500 response.
Bedigas::notFound() // Sends an HTTP 404 response.
Bedigas::etag($id, [$type]) // Performs ETag HTTP caching.
Bedigas::lastModified($time) // Performs last modified HTTP caching.
Bedigas::json($data, [$code], [$encode], [$charset], [$option]) // Sends a JSON response.
Bedigas::jsonp($data, [$param], [$code], [$encode], [$charset], [$option]) // Sends a JSONP response.

使用mapregister添加的任何自定义方法也可以进行过滤。

框架实例

您可以选择将Bedigas作为对象实例而不是全局静态类运行。

require 'bedigas/autoload.php';

use bedigas\Engine;

$app = new Engine();

$app->route('/', function(){
    echo 'hello world!';
});

$app->start();

因此,您将调用Engine对象上与静态方法相同的名称的实例方法,而不是调用静态方法。