Home > database >  non static method can't be called statically
non static method can't be called statically

Time:09-26

I am so lost with how to get this working. All I want to do is to be able to call a function from another class and return the value.

in livewire component

use Livewire\Component;
use App\Actions\Broadcast\GetCurrentActiveTimeSlotAction;

class DisplayLiveBroadcastCard extends Component
{
    public $timeSlot;

    public function mount()
    {
        $this->refreshTest();

        dd($this->timeSlot);
    }

    public function refreshTest()
    {
        $this->timeSlot = GetCurrentActiveTimeSlotAction::execute();
    }

inside the GetCurrentActiveTimeslot class

class GetCurrentActiveTimeSlotAction
{
    public $test;

    public function __construct()
    {
        $this->test = 5;
    }

    public function execute()
    {
        $value = $this->test;
        return $value;
    }
}

Yes, I did rename it to static function execute() but that broke another thing where now I get an error trying this

static function execute()
    {
        $value = $this->test;
        return $value;
    }

Alternatively, I tried this approach as well, ut now it says I need to pass a variable into the refreshTest function. Which I understand, but anything I pass in there seems to break it.


public function mount()
    {
        $this->refreshTest();

        dd($this->timeSlot);
    }

    public function refreshTest(GetCurrentActiveTimeSlotAction $getCurrentActiveTimeSlotAction)
    {
        $this->timeSlot = $getCurrentActiveTimeSlotAction->execute();
    }

Looking for any advice on how I can just do a calculation in the GetCurrentActiveTimeSlotAction and return the value inside the livewire component.

CodePudding user response:

Assuming you don't want to do the trivial thing (e.g. $this->timeSlot = (new GetCurrentActiveTimeSlotAction)->execute();) and want to do dependency injection instead (because that will make your code more testable) then you can inject objects in your mount method (source):

use Livewire\Component;
use App\Actions\Broadcast\GetCurrentActiveTimeSlotAction;

class DisplayLiveBroadcastCard extends Component
{
    public $timeSlot;
    private $activeTimeslotActionGetter;

    public function mount(GetCurrentActiveTimeSlotAction $getter)
    {
        $this->activeTimeslotActionGetter = $getter;
        $this->refreshTest();

        dd($this->timeSlot);
    }

    public function refreshTest()
    {
        $this->timeSlot = $this->activeTimeslotActionGetter->execute();
    }
  • Related