swisschili / ezweb

一个专为讨厌PHP框架的人设计的微型PHP框架

dev-master 2020-08-27 15:51 UTC

This package is not auto-updated.

Last update: 2024-09-20 14:15:56 UTC


README

巨大的PHP框架很糟糕。至少这是我个人的看法,这就是我为什么做这个。我的目标是创建一个尽可能小的、能满足我需求的PHP框架。

到目前为止,它包括一个路由器和模板引擎。

示例

<?php // migration.php

require_once __DIR__ . "/vendor/autoload.php";

use \SwissChili\Migrations;

// Gets all the files in migrations/ with the format
// <version>-up|down and stores them in an array of
// name to contents
$files = Migrations::getFiles(__DIR__ . "/migrations");
// Create a new migrations object with current version 1
// and migrations $files (in reality you should get the
// current version from your database or from some file)
$m = new Migrations(1, $files);

// This will apply migrations 1-up, 2-up, and 3-up.
// If target version < current version it will look
// for N-down mirgations
$m->mirgate(4, function ($code)
{
	// Apply the migration in whatever way you usually do
	$myDbConnection->executeSql($code);
});
<?php // public/index.php

require_once __DIR__ . '/../vendor/autoload.php';

use \SwissChili\Router;
use \SwissChili\Templates;

$t = new Templates(__DIR__ . "/../templates");

Router::get('/', function () {
	echo 'home';
});

Router::get('/names/:name', function ($name) use ($t) {
	echo $t->render("home", ["name" => $name]);
});

Router::failure(function () {
	echo "404 Not Found";
});
<!-- templates/home.php -->

<?php $this->layout('layout', ["title" => "<b>My</b> Site"]) ?>

<h1>Hello, <?= $name ?></h1>
<!-- templates/layout.php -->

<title><?= $this->e($title) ?></title>

<?= $content ?>

<hr>

Footer

参考

路由器是50行代码,模板引擎是70行。如果你想更详细地了解它们是如何工作的,只需阅读代码即可。它应该相当容易理解。

以下是一些相关的函数

路由器

  • Router::route($method, $route, $func) 当通过HTTP方法 $method 对 $route 进行请求时,调用 func
  • Router::get, post, put, 等等,所有的HTTP方法都有类似于 route() 的辅助函数,但不包括 $method 参数
  • Router::failure($func) 如果尚未匹配路径,则调用 $func。在所有路由处理程序之后调用以处理404。

模板

  • new Templates($path) 将 $path 设置为模板的基本路径
  • Templates::render($name, $args) 使用 $args 渲染名为 $name 的模板

在模板中,$this 指的是 View 的一个实例

  • View::layout($name[, $args]) 为此模板设置布局。
  • View::e($data) HTML转义 $e
  • View::include($name[, $args]) 使用 $args 包含模板 $name

迁移

  • Migrations::getFiles($dir) 在 $dir 中查找所有以 <number>-up|down 开头的文件。例如:3-up-add-users-table.sql
  • new Migrations($version, $migrations) 使用当前版本 $version 和迁移 $migrations 创建一个新的迁移对象。
  • Migrations::migrate($version, $func) 通过为迁移的每个步骤调用 $func 迁移到 $version。