虽然我对接口和抽象类有一点了解,但我对OOP还有点陌生。我有很多资源控制器,它们在更大的方案上有点相似,它们看起来都像下面的例子,唯一的主要区别是索引和我传递给索引视图的内容。
我只需要知道的是,我能用我的资源控制器做一些事情吗?例如,创建一个“主”资源控制器,其中我只是使用一个接口传递正确的实例。我试着玩这个,但是我得到了一个错误,接口不能实例化,所以我不得不绑定它。但这意味着我只能将接口绑定到特定的控制器。
任何建议、建议和建议都能帮到我:)
class NotesController extends Controller
{
public function index()
{
$notes = Note::all();
return view('notes.index', compact('notes'));
}
public function create()
{
return view('notes.create');
}
public function show(Note $note)
{
return view('notes.show', compact('note'));
}
public function edit(Note $note)
{
return view('notes.edit', compact('note'));
}
public function store(Request $request, User $user)
{
$user->getNotes()->create($request->all());
flash()->success('The note has been stored in the database.', 'Note created.');
return Redirect::route('notes.index');
}
public function update(Note $note, Request $request)
{
$note->update($request->all());
flash()->success('The note has been successfully edited.', 'Note edited.');
return Redirect::route('notes.index');
}
public function delete($slug)
{
Note::where('slug', '=', $slug)->delete();
return Redirect::to('notes');
}
}发布于 2016-02-08 12:27:37
注:完全是我的意见!
我会让他们和你一样。这会使他们以后更容易阅读和理解。另外,当你需要更新一个来做与其他事情不同的事情时,也会节省你的时间。我们在我做过的一个项目中尝试了这一点,虽然它不是最好的实现,但它至今仍然是一个痛点。
不过还是看你的吧。我敢肯定,人们这样做的方式,他们喜欢和工作的伟大。只是在我的经验中不是这样的。不过,我怀疑有人会看你的代码,并批评你没有这么做。
发布于 2016-02-08 13:02:29
如果您需要绑定不同的模型实例,那么可以使用上下文绑定,例如,将以下代码放入AppServiceProvider'的寄存器()方法中:
$this->app->when('App\Http\Controllers\MainController')
->needs('Illuminate\Database\Eloquent\Model')
->give(function () {
$path = $this->app->request->path();
$resource = trim($path, '/');
if($pos = strpos($path, '/')) {
$resource = substr($path, 0, $pos);
}
$modelName = studly_case(str_singular($resource));
return app('App\\'.$modelName); // return the appropriate model
});在控制器中,使用__construct方法注入模型,如下所示:
// Put the following at top of the class: use Illuminate\Database\Eloquent\Model;
public function __construct(Model $model)
{
$this->model = $model;
}然后你可以使用这样的东西:
public function index()
{
// Extract this code in a separate method
$array = explode('\\', get_class($this->model));
$view = strtolower(end($array));
// Load the result
$result = $this->model->all();
return view($view.'.index', compact('result'));
}希望您有了这个想法,所以执行其余的方法。
https://stackoverflow.com/questions/35268668
复制相似问题