我对如何使用合同感到困惑。我认为这是因为我还没有使用过单元测试,所以对我而言,合同的运作方式并不明显。
让我们看一下这段代码:
use Illuminate\Contracts\Auth\Guard;
...
public function __construct(Guard $auth)
{
$this->auth = $auth;
$this->middleware('guest', ['except' => 'getLogout']);
}
public function postRegister(RegisterRequest $request)
{
// Registration form is valid, create user...
$this->auth->login($user);
return redirect('/');
}
那么我怎么知道哪一个类在这一行中实现了login
合同方法:$this->auth->login($user)
?如果我想使用自己的课程,如何更改课程?
在laravel 4中,我写了Auth::user()
作为一个例子,我在任何控制器的任何地方都使用它,它起作用了。现在我应该在控制器方法中注入一个契约并像$auth->user
一样使用它?
此外,如果我做对了,合同用于制作抽象。好的,所以,如果我想为我自己的类构建一个新的接口,然后有多个实现我的接口的类,我应该在哪里编写代码?我无法想到一个例子,但我想我需要实现一个启用/禁用灯泡的界面,我有两种方法,如on()
和off()
,我有多种方法可以做那。我是否需要为此创建新合同?
答案 0 :(得分:7)
我希望我能让你对此更加清楚......
Ad.1。您可以在/vendor/laravel/framework/src/Illuminate/Foundation/Application.php
处检查默认绑定(第792行附近的方法registerCoreContainerAliases
)。如果您想创建自己的类或扩展现有类,我建议您查看How to extend Laravel's Auth Guard class?或http://laravel.com/docs/master/extending(这个更多是关于Laravel 4.x但可能会给您一个想法)。
Ad.2。实际上你仍然可以使用Auth :: user(),但我在构造函数或方法中注入一个契约,并将其称为$ this-> auth-> user或$ auth-> user。
Ad.3。我有一个/app/Repositories
文件夹,我放置了我的界面和实现,所以为了按照你的例子,我将创建子文件夹Lamp
,我将创建LampInterface
on()
和{{1}方法,然后我会创建类似Lamp.php的实现off()
的东西。接下来,我将在LampInterface
中创建一个服务提供者,如LampServiceProvider.php,带有绑定:
/app/Providers
之后我会在/app/config/app.php中注册新的服务提供商,最后我可以注入我的界面:
namespace Apps\Providers;
use Illuminate\Support\ServiceProvider;
class LampServiceProvider extends ServiceProvider {
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton(
'App\Repositories\Lamp\LampInterface',
'App\Repositories\Lamp\Lamp'
);
}
}