首页 > 解决方案 > Slim 3 条件路由

问题描述

我跑到墙上,现在我的头很痛。

有这条路线将数据返回给用户。

 $this->get('/getdata', 'DataController:SweetData');

控制器做它的事情并返回数据,我试图根据条件将这个单一的路由路由到不同的控制器。

例如,如果用户来自特定的 IP 地址,我希望他使用不同的控制器。我在想这样的事情:

 $this->get('/getdata', function ($request, $response) {
   ** DO SOME CONDITIONAL MAGIC AND SEND IT TO CONTROLLER ** 
 };

我的问题是,我不确定如何在条件魔法之后将其发送到不同的控制器。

谢谢。

标签: phpframeworksslim

解决方案


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

推荐阅读