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 ?
2
Answers
Since I wanted to decouple my PostForm from CreatePost component and also wanted to follow the DI principle so I made an interface of PostService and use in the PostForm store method. I used ServiceProvider to provide concrete implementation of my Service class. It was so simple but didn't came in my mind.
You can do it in mount() method
If needed add customizations in AppServiceProvider::register