如何解决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.";
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。