【问题标题】:how can i use __construct in conjuction with controller in laravel我如何在 laravel 中将 __construct 与控制器结合使用
【发布时间】:2016-01-06 18:23:44
【问题描述】:

我已经在 Laravel 4 和 Laravel 5 中构建了 laravel 应用程序,但这次我决定先编写我所有的测试,以前从未为琐碎的应用程序编写过测试。

这是我的 Account 类 - 用于说明

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', 'AccountController@index');

但这就是问题所在。实际上尝试运行一个页面来获取帐户列表是很麻烦的。我知道控制器类还有很多事情要做,但这就是我所拥有的。

<?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() 之前,一切正常。

谢谢。

【问题讨论】:

    标签: php unit-testing laravel-5.2 construct


    【解决方案1】:

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

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

    如果您想使用这些变量来创建新模型,请查看 $fillable

    【讨论】:

    • 感谢您回来......不过我不确定我是否关注。我要做的是检索所有帐户的列表... $accountModel 不只是一个新的 Account 实例吗?
    • 嗯,你是对的。你想用 __construct 完成什么?
    • __construct 被设置为适应 phpUnit 中的 setup() 方法进行单元测试。我并不是特别喜欢它,只是因为我认为我的测试需要它来将它们重构为更易于管理的东西。
    • 好的,所以看起来我正在覆盖核心 __construct 方法。我不想;当我对该主题知之甚少时,遵循教程是不受欢迎的副作用!我在 laracasts 论坛上得到了一些帮助,所以我会在这里发布进度
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2016-04-29
    相关资源
    最近更新 更多