如何调用具有依赖关系的自定义类?

时间:2018-06-27 09:15:54

标签: laravel dependency-injection inversion-of-control

假设我有一个控制器,它将使用 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();
    }
}

如何像在控制器内部一样完成这些类的调用?

0 个答案:

没有答案