更好的做法是采用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.";
}
}