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 MyAppControllersMyController;
$app->get('/getdata', [MyController::class , 'sweetData']);

/src/Controllers/MyController.php:

<?php
namespace MyAppControllers;
use PsrHttpMessageServerRequestInterface as Request;
use PsrHttpMessageResponseInterface as Response;
use MyAppServicesMyService;
use MyAppServicesOtherService;
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 MyAppServices;
class MyService
{
public function doSomething(string $data)
{
# $data would be "apple"
return "Apples are delicious.";
}
}

/src/Services/OtherService.php:

<?php
namespace MyAppServices;
class OtherService
{
public function doSomething(string $data)
{
# $data would be "orange"
return "Oranges are delicious.";
}
}

最新更新