You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Slim 3 如何向控制器方法传递额外参数(如$tokenAuth)

Got it, let's break down how to pass your $tokenAuth object to your controller method in Slim (since your code looks like Slim framework syntax). Here are a few solid approaches, ordered by best practice:

Slim is built around a dependency injection container, which is the cleanest way to handle this. First, register your $tokenAuth instance with the container:

// When initializing your Slim app
$container = $app->getContainer();

// Bind your existing $tokenAuth object to the container
$container['tokenAuth'] = function ($c) use ($tokenAuth) {
    return $tokenAuth;
};

Then, you can inject it into your controller in two ways:

Option A: Constructor Injection (Most Elegant)

Inject $tokenAuth directly into your controller's constructor, so it's available to all methods:

class UserController {
    private $tokenAuth;

    public function __construct($tokenAuth) {
        $this->tokenAuth = $tokenAuth;
    }

    public function add(Request $request, Response $response, array $args) {
        $this->tokenAuth->parseHeaders(); // Use the injected object
        // ... your logic here
        $response->getBody()->write(json_encode(['status' => 'success']));
        return $response;
    }
}

Option B: Method Injection

If you only need $tokenAuth in the add method, declare it as a parameter (the container will auto-resolve it):

class UserController {
    public function add(Request $request, Response $response, array $args, $tokenAuth) {
        $tokenAuth->parseHeaders();
        // ... your logic here
        return $response;
    }
}

2. Wrap the Controller Call in a Closure

If you don't want to mess with the container right now, you can fall back to a closure wrapper that passes $tokenAuth manually:

$app->post('/api/user', function (Request $request, Response $response, array $args) use ($tokenAuth) {
    $controller = new UserController();
    return $controller->add($request, $response, $args, $tokenAuth);
});

This works, but it's less scalable than dependency injection if you have multiple controllers/methods needing $tokenAuth.

3. Use a Middleware (Great for Token Validation)

Since you're using $tokenAuth to parse/validate headers, this logic is a perfect fit for a middleware—it keeps your controller focused on business logic instead of auth checks:

// Create the middleware
$tokenAuthMiddleware = function (Request $request, RequestHandler $handler) use ($tokenAuth) {
    $tokenAuth->parseHeaders();
    
    // Add validation logic here (e.g., check if token is valid)
    if (!$tokenAuth->isValid()) {
        $response = new Response();
        $response->getBody()->write(json_encode(['error' => 'Unauthorized']));
        return $response->withStatus(401);
    }

    // Pass the request to the controller if validation passes
    return $handler->handle($request);
};

// Attach the middleware to your route
$app->post('/api/user', \UserController::class . ':add')->add($tokenAuthMiddleware);

With this approach, your controller doesn't even need to know about $tokenAuth—the middleware handles the auth check before the controller runs.

内容的提问来源于stack exchange,提问作者dale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:07:09