doubei5310 2015-11-01 23:46
浏览 81
已采纳

Silex控制器依赖注入

I'm trying to inject a dependency into my Silex Controller, because I need an object of type user in my controller and handle some stuff with it.

$app->mount("/users", new \MyApp\Controller\Provider\User($user));

And I implemented the controller by implementing the ControllerProviderInterface:

class User implements ControllerProviderInterface{
    protected $user;

    public function __construct($user){
        //...
    }

    public function connect(Application $app)
    {
        //...
    }
}

The routes and the methods are all set up in the controller. Without the dependency injection everything works fine. But as long as I edit the code and add the injection I get the following error:

Missing argument 1 for ...::__construct()

When I create the object, I send that parameter to it, but somehow Silex creates an instance before with a constructor without passing any argument.

  • 写回答

3条回答 默认 最新

  • doulu1544 2015-11-03 00:07
    关注

    Another approach is to use a ServiceController instead of a ControllerProvider. You can achieve a more familiar dependency injection feel this way.

    $app->register(new Silex\Provider\ServiceControllerServiceProvider());
    
    $app["user"] = function () {
        return new User();
    };
    $app["user.controller"] = function () use ($app) {
        return new UserController($app["user"]);
    };
    
    $app->get("/users/{id}", "user.controller:get");
    

    ...

    class User implements UserInterface
    {
        // ...
    }
    

    ...

    class UserController
    {
        protected $user;
    
        public function __construct(UserInterface $user)
        {
            $this->user = $user;
        }
    
        public function get(Request $request, $id)
        {
            $this->user;
    
            // Do stuff
        }
    }
    

    Reference: http://silex.sensiolabs.org/doc/providers/service_controller.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器