lim6112j / apicenter
此包的最新版本(0.2)没有提供许可证信息。
API中心
0.2
2021-07-19 08:50 UTC
Requires
- php: >=7.4
This package is auto-updated.
Last update: 2024-09-25 21:01:58 UTC
README
用法
服务器设置
- 为了设置pretty url,启用rewritable选项
- 创建.htaccess文件
- 将.htaccess文件放置在public文件夹中
- 服务器设置可能有所不同。
开始使用模板项目
- 安装composer
- 安装node
- 移动到服务器上可服务的文件夹,如www,htdocs等,并执行以下命令。(将newProject替换为您的项目名称)
composer create-project -s dev lim6112j/apicenter newProject
- 将./newProject/dist文件夹设置为服务器的document root。(npm run build后自动生成。)
- 在终端中进入newProject文件夹,执行composer update和npm
composer update npm install npm run build
- 检查localhost是否运行。
添加新页面的方法
- 在[document root]/index.php中添加将添加的页面route。如下所示,则可以通过/newpage和/newpage.php两种方式访问。
// https:///newpage로 요청이오면 DefaultController에 있는 newpage 함수를 실행하라.
$app->router->get('/newpage', [DefaultController::class, 'newpage']);
$app->router->get('/newpage.php', [DefaultController::class, 'newpage']);
- 打开DefaultController.php,添加以下函数。
public function newpage(): string
{
$params = ['name' => 'the cheat'];
return $this->render('newpage', $params); // views 폴더에서 newpage.php를 찾아 렌더링.
}
- 在/views文件夹中创建以下将渲染的newpage.php文件。
- 通过$params传递的$name变量将显示其值。
<h1>Hello <?php echo $name ?></h1>
添加新中间件的方法 - NewMiddleware
- 为了阻止api认证,为DefaultController管理的api添加新的认证,并在显示结果之前通过新的中间件进行处理。
- 在/middleware中创建NewMiddleware.php文件
<?php
namespace app\middlewares;
use app\core\BaseMiddleware;
class NewMiddleware extends BaseMiddleware
{
//BaseMiddleware에서 상속된 필수 구현 함수.
public function execute()
{
if(something wrong) {
exit;
}
}
}
- 在index.php的routing信息中添加以下内容。
$app->router->get('/', [DefaultController::class, 'home'],[LoginMiddleware::class, NewMiddleware::class]);
- 在上面的代码中,可以从LoginMiddleware创建的数据在NewMiddleware中使用。从左到右传递数据。
- 现在,由DefaultController管理的api将在执行NewMiddleware的execute函数后发送响应。
- 所有中间件都可以作为数据源使用。
class AuthMiddleware extends BaseMiddleware
{
protected static $_instance = null;
public static function getInstance()
{
if (static::$_instance === null)
{
static::$_instance = new static();
}
return static::$_instance;
}
public function execute():array
{
$login_array['now_year'] = date("Y");
$login_array['now_month'] = date("m");
return $login_array;
}
}
- 上述源可以在页面中使用$login_array。
- 在execute函数内添加redirection以用于认证。
public function execute($data=[]):array { ($data['member_uid'] && $data['member_uid']>0) ?: header('Location:/login'); return $data; }
数据库相关查询添加
- DB设置数据是从config.php中获取的。
- 所有DB相关函数都集中在/models文件夹中。
- $db变量被设计成单例,在整个request->response过程中只使用一个。
中间件通过继承BaseMiddleware使用单例。
- 在为单个request创建response之前调用api等时,由于controller发生变化,中间件会重新注入,因此避免了重复实例化。
- 中间件必须始终返回数组。如果没有返回值,也请像下面这样写。
... return [];