dtol41388 2014-12-15 05:43
浏览 155
已采纳

构造函数依赖注入如何在Laravel中工作?

I am using Laravel. I knew we can write constructor dependency injection as below code. I am wondering how it is working? I mean how constructor get $post and $user model objects? How it is injected?

    /**
     * Inject the models.
     * @param Post $post
     * @param User $user
     */
    public function __construct(Post $post, User $user)
    {
        parent::__construct();

        $this->post = $post;
        $this->user = $user;
    }

Please explain me. Thanks.

  • 写回答

1条回答 默认 最新

  • dongluo1853 2014-12-18 05:43
    关注

    Laravel IoC uses a process called Autowiring. This is something that is very common in other languages and other PHP IoC containers.

    The idea is to look at the constructor parameters using PHP's Reflection API. Using that, Laravel can see that $post needs to be a Post instance and thus it will create it on the fly. In short, Laravel will do something like this:

    $post = new Post();
    $user = new User();
    $obj = new TheClass($post, $user);
    

    (if you wonder how it will find the Post class: the Composer autoloader will autoload it based on your configuration in composer.json)

    This process works well with Services (i.e. "utility" classes like the Database, Logger, etc.) but it doesn't work with Model classes.

    The reason for this is simple: Laravel can't know which post and user you want to inject (assuming there are several in your database). Instead you should fetch those instances from the database and pass them around yourself.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示