skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    app(PostServiceInterface::class)
    

  2. You can do it in mount() method

    class Foo extends Component
    {
        protected LoggerInterface $logger;
    
        public function mount(LoggerInterface $logger)
        {
            $this->logger = $logger;
        }
    
        public function render()
        {
            $this->logger->info('component rendered');
            return view('livewire.foo');
        }
    
        public function action()
        {
            $this->logger->info('action triggered');
        }
    }
    

    If needed add customizations in AppServiceProvider::register

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search