我对如何使用合同有点困惑。我想这是因为我没有使用单元测试,所以对我来说合同是如何工作的并不明显。
让我们看看这个代码:
use IlluminateContractsAuthGuard;
...
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()
,我有多种方法可以做到这一点。我需要为此创建新合同吗?
我希望我能让你更清楚一点。。。
Ad.1.您可以在/vendor/laravel/framework/src/Illuminate/Foundation/Application.php
处检查默认绑定(方法registerCoreContainerAliases
围绕第792行)。如果你想创建自己的类或扩展现有的类,我建议你看看如何扩展Laravel';s Auth Guard类?或http://laravel.com/docs/master/extending(这篇文章更多的是关于Laravel 4.x,但可能会给你一个想法)。
Ad.2.实际上你仍然可以使用Auth::user(),但我在构造函数或方法中注入了一个契约,并像$this->Auth->user或$Auth->user那样调用它。
Ad.3.我有一个/app/Repositories
文件夹,我把接口和实现放在那里,所以按照你的例子,我会创建子文件夹Lamp
,我会用on()
和off()
方法创建LampInterface
,然后我会创建一些类似Lamp.php的东西来实现LampInterface
。接下来,我将在/app/Providers
中创建一个服务提供商,如LampServiceProvider.php,带有绑定:
namespace AppsProviders;
use IlluminateSupportServiceProvider;
class LampServiceProvider extends ServiceProvider {
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton(
'AppRepositoriesLampLampInterface',
'AppRepositoriesLampLamp'
);
}
}
之后,我会在/app/config/app.php中注册新的服务提供商,最后我可以注入我的接口,比如:
public function switchLampOn(AppRepositoryLampLampInterface $lamp)
{
$lamp->on();
}