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.

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

报告相同问题?

悬赏问题

  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误