startmvc Request类使用的示例

startmvc php框架学习社区

技术交流社区
startmvc Request类使用的示例
admin 普通会员 时间:2025-09-09 20:15:29 浏览:83

namespace app\home\controller;

use app\common\BaseController;
use startmvc\core\Request;

class ExampleController extends BaseController
{
 /**
 * 登录处理 - 展示统一的静态调用
 */
 public function loginAction()
 {
 // 现在所有方法都支持静态调用,使用更加一致
 if (Request::isPost()) {
 $username = Request::input('username');
 $password = Request::input('password');
 
 if ($username && $password) {
 // 处理登录逻辑
 $this->success('登录成功');
 } else {
 $this->error('用户名密码不能为空');
 }
 } else {
 $this->display();
 }
 }
 
 /**
 * API接口 - 展示AJAX判断
 */
 public function apiAction()
 {
 // 统一的静态调用方式
 if (Request::isAjax()) {
 $data = Request::all();
 $userAgent = Request::header('User-Agent');
 
 $response = [
 'method' => Request::method(),
 'data' => $data,
 'userAgent' => $userAgent,
 'ip' => Request::ip(),
 'isHttps' => Request::isHttps()
 ];
 
 $this->json($response);
 } else {
 $this->error('只支持AJAX请求');
 }
 }
 
 /**
 * 用户信息获取
 */
 public function getUserAction()
 {
 if (Request::isGet()) {
 $id = Request::get('id');
 $format = Request::input('format', 'json');
 
 if ($id) {
 // 模拟获取用户数据
 $userData = [
 'id' => $id,
 'name' => 'Test User',
 'format' => $format
 ];
 
 $this->json($userData);
 } else {
 $this->error('用户ID不能为空');
 }
 }
 }
 
 /**
 * 文件上传处理
 */
 public function uploadAction()
 {
 if (Request::isPost()) {
 // 检查内容类型
 $contentType = Request::header('Content-Type');
 
 if (strpos($contentType, 'application/json') !== false) {
 // 处理JSON数据
 $jsonData = Request::getJson();
 $this->json(['message' => 'JSON数据接收成功', 'data' => $jsonData]);
 } else {
 // 处理表单数据
 $file = Request::post('file');
 $description = Request::input('description', '无描述');
 
 $this->json([
 'message' => '表单数据接收成功',
 'file' => $file,
 'description' => $description
 ]);
 }
 } else {
 $this->display();
 }
 }
}


回复列表
0个回复