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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?