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条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算