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 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思