I have a Component called CreatePost
class CreatePost extends Component
{
public PostForm $form;
public function save()
{
$this->form->store();
return $this->redirect('/posts');
}
}
And Here is my PostForm:
class PostForm extends Form
{
public $title = '';
public $content = '';
public function store()
{
$this->validate();
Post::create($this->all());
}
}
Now in my PostForm store() method I want to inject my PostService to create a Post. What is the best way to do it.
Thanks
Best I could come up with is to Inject my PostService in boot() method of my Component and then pass it as a parameter in store() but I was hoping if there is a cleaner way to do it through ServiceProvider for example ?
Since I wanted to decouple PostForm
from CreatePost
component and also wanted to follow the DI principle so I made an interface of PostService
and used that in the PostForm
store()
method. I used Laravel ServiceProvider to provide concrete implementation of Service class. It was so simple but didn't came in my mind.
app(PostServiceInterface::class)