2016-01-06 27 views
1

我已经在Laravel 4和Laravel 5中构建了laravel应用程序,但是我决定先这样写所有的测试,以前从来没有编写过测试应用程序。我如何在laravel中使用__construct与控制器结合使用

这里是我的账户类 - 用于说明

class Account extends Model 
{ 
    protected $customer_id; 
    protected $bookmaker_id; 
    protected $balance; 
    protected $profit; 

    public function __construct($customer_id, $bookmaker_id, $balance, $profit) { 
     $this->customer_id = $customer_id; 
     $this->bookmaker_id = $bookmaker_id; 
     $this->balance = $balance; 
     $this->profit = $profit; 
     } 
} 

所以我所有的单元测试运行良好:

我的路线是正确的设置为我想要显示

Route::get('/accounts', '[email protected]'); 
页面

但这是它出错的地方。实际上试图运行一个页面来获取帐户列表是很麻烦的。我知道还有更多的控制器类,但这里是我的。

<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

use App\Http\Requests; 
use App\Http\Controllers\Controller; 
use App\Account; 

class AccountController extends Controller 
{ 
    /** 
    * Display a listing of the resource. 
    * 
    * @return \Illuminate\Http\Response 
    */ 
    public function index() 
    { 
     $accounts = Account::all(); 
     return view('account.index', compact('accounts')); 
    } 
} 

然后我得到这个错误 -

ErrorException in Account.php line 14: 
Missing argument 1 for App\Account::__construct(), called in /Applications/MAMP/htdocs/mb-app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 665 and defined 

有人能告诉我,我应该怎么设置我的控制器吗?直到我为我的单元测试添加了__construct(),这一切都会好起来的。

谢谢。

回答

0

通过使用__construct,它在任何时候初始化参数都需要参数。因此,相反,你会使用

$accountModel = new Account($customer_id, $bookmaker_id, $balance, $profit); 
$accounts = $accountModel->all(); 

如果你想使用这些变量来创建一个新的模式,看看$fillable

+0

感谢您回复...不知道我按照。我想要做的是检索所有帐户的列表...不会$ accountModel只是一个新的帐户实例? – dstewart101

+0

嗯,你是对的。你想用__construct完成什么? – aynber

+0

__construct被设置为适应phpUnit中的setup()方法进行单元测试。我并不特别关注它,只是我认为我需要它来进行测试,将它们重构成更可管理的东西。 – dstewart101

相关问题