相关疑难解决方法(0)

Laravel依赖注入:你什么时候需要?你什么时候可以模仿外墙?两种方法的优点?

我已经使用Laravel一段时间了,我已经阅读了很多关于依赖注入的可测试代码.在谈到Facades和Mocked Objects时,我已经陷入了困惑.我看到两种模式:

class Post extends Eloquent {

    protected $guarded = array();

    public static $rules = array();

}
Run Code Online (Sandbox Code Playgroud)

这是我的帖子模型.我可以跑来Post::all();从我的博客上获取所有帖子.现在我想将它合并到我的控制器中.


选项#1:依赖注入

我的第一直觉是将Post模型作为依赖注入:

class HomeController extends BaseController {

    public function __construct(Post $post)
    {
    $this->post = $post;
    }

    public function index()
    {
        $posts = $this->posts->all();
        return View::make( 'posts' , compact( $posts );
    }

}
Run Code Online (Sandbox Code Playgroud)

我的单元测试看起来像这样:

<?php 

use \Mockery;

class HomeControllerTest extends TestCase {

    public function tearDown()
    {
        Mockery::close();

        parent::tearDown();
    }
    public function testIndex()
    {
        $post_collection = new StdClass();

        $post = …
Run Code Online (Sandbox Code Playgroud)

php unit-testing dependency-injection mockery laravel-4

16
推荐指数
1
解决办法
6711
查看次数