假设我有一个控制器,它将使用 CreateAction 和 EditAction 类,并且我想在 Store 和<像这样的strong>编辑方法:
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\Posts\StoreRequest;
use App\Action\Posts\EditAction;
use App\Action\Posts\CreateAction;
class PostController extends Controller
{
public function index()
{
return view('posts.index');
}
public function create()
{
return view('posts.create');
}
public function store(StoreRequest $request)
{
$post = $this->execute(new CreateAction(), $request->validated());
return redirect()->route('posts.edit', $post->id);
}
public function edit($id)
{
$post = $this->execute(new EditAction(), $id);
return view('posts.edit', compact('post'));
}
}
EditAction 的示例:
namespace App\Actions\Posts;
use App\Models\Post;
class EditAction
{
private $post;
public function __construct(Post $post)
{
$this->model = $post;
}
public function execute($id)
{
return $this->model->where('id', $id)->firstOrFail();
}
}
如何像在控制器内部一样完成这些类的调用?