Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

php - Using traits with livewire

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...