Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm building livewire components that shares 50% of public properties and almost 90% of submit function logic.

each component using this trait has its own rules according to its html-form fields. and also each component perform some custom logic after validating the data. other that that they are all the same.

<?php

namespace AppTraits;

 trait ParentServiceComponent
 {

   public $desc = '';

   public function rules()
   {
      return [
          'desc' => 'required|max:2000'
      ];
   }

  public abstract function componentCustomLogic(array $data);

  public function submit()
  {
    $data = $this->validate();
    
    $performCusomLogic = $this->componentCustomLogic($data);
    
    // save to db and show success message
  } 
}

here an example of two components that uses this trait.

<?php

namespace AppHttpLivewire;

use LivewireComponent;

use AppTraitsParentServiceComponent;

class RequestService extends Component
{

    public $type = '';

    use ParentServiceComponent { rules as traitRules; }

    public function rules()
    {
        return array_merge($this->traitRules, [
            'type' => 'required|max:200'
        ]);
    }

    public function componentCustomLogic(array $data)
    {
        // do the logic of this component here
    }

    public function render()
    {
        return view('livewire.request-service');
    }
}

<?php

namespace AppHttpLivewire;

use LivewireComponent;

use AppTraitsParentServiceComponent;

class ReplyService extends Component
{

    public $body = '';

    use ParentServiceComponent { rules as traitRules; }

    public function rules()
    {
        return array_merge($this->traitRules, [
            'body' => 'required|max:200'
        ]);
    }

    public function componentCustomLogic(array $data)
    {
        // do the logic of this component here
    }

    public function render()
    {
        return view('livewire.reply-service');
    }
}

so my question is: am I doing it right?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...