php - Slim 3 条件路由
问题描述
我跑到墙上,现在我的头很痛。
有这条路线将数据返回给用户。
$this->get('/getdata', 'DataController:SweetData');
控制器做它的事情并返回数据,我试图根据条件将这个单一的路由路由到不同的控制器。
例如,如果用户来自特定的 IP 地址,我希望他使用不同的控制器。我在想这样的事情:
$this->get('/getdata', function ($request, $response) {
** DO SOME CONDITIONAL MAGIC AND SEND IT TO CONTROLLER **
};
我的问题是,我不确定如何在条件魔法之后将其发送到不同的控制器。
谢谢。
解决方案
更好的做法是采用Route
> Controller
> Service
>的模式Model
。如果需要,您可以跳过模型,但这是重用代码并遵守 DRY 原则的好方法(不要重复自己)。
我会说你的头很痛,因为你越过了你的控制器的界限。控制器就是这样,控制器——这就是你应该定义你的“条件魔法”的地方。
一般来说,我建议您保持控制器轻量级——使用它们来简单地收集查询参数、验证有效的请求主体并调用适当的服务。您的主要业务逻辑应该存在于您的服务中。使用模型在您的服务之间共享通用的可重用代码。
/src/Routes/MyRoute.php
:
<?php
use MyApp\Controllers\MyController;
$app->get('/getdata', [MyController::class , 'sweetData']);
/src/Controllers/MyController.php
:
<?php
namespace MyApp\Controllers;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use MyApp\Services\MyService;
use MyApp\Services\OtherService;
class MyController
{
protected $myService;
protected $otherService;
public function __construct(MyService $myService, OtherService $otherService)
{
$this->myService = $myService;
$this->otherService = $otherService;
}
public function sweetData(Request $request, Response $response)
{
# perform your conditional magic and call your appropriate service
$someParam = (string)$request->getQueryParam("something");
if ($someParam === "apple") {
return $response->withJson($this->myService->doSomething($someParam));
}
elseif ($someParam === "orange") {
return $response->withJson($this->otherService->doSomething($someParam));
}
}
}
/src/Services/MyService.php
:
<?php
namespace MyApp\Services;
class MyService
{
public function doSomething(string $data)
{
# $data would be "apple"
return "Apples are delicious.";
}
}
/src/Services/OtherService.php
:
<?php
namespace MyApp\Services;
class OtherService
{
public function doSomething(string $data)
{
# $data would be "orange"
return "Oranges are delicious.";
}
}
推荐阅读
- python - 获取文本中名词的性别?
- automata - 我想做一个 CFG,其中字母 b 永远不会三倍
- c# - 从 SQL 脚本重新创建 LINQ 查询的问题
- laravel-5.8 - 部署的 Laravel 项目未运行
- javascript - 在 react native 中使用 this.props.children 加载大组件时是否存在任何性能问题?
- c# - 如何使用嵌套循环在 C# 中以 Windows 形式生成 00001
- docker - 集成两个 docker 应用 - Docker compose 和 Docker run
- php - ErrorException 未定义变量:post
- c# - 列表集合 addRange 多个项目
- c++ - Problem in testing my function with Catch2Farmework