garrettmassey's avatar

Extending a composer package with custom methods in Laravel

I am using a spatie package called "Opening Hours" to handle schedules in this project, and I have written a custom function that calls an existing OpeningHours method in a loop to determine if a business is open on the days listed in an input array.

Long story short, if I put my code directly into the OpeningHours class in the vendor package, it works, but I don't want my code to exist inside a package where it could be erased if the package is updated or if I run composer update or composer upgrade, I want my code to exist in a class that extends the OpeningHours class.

What I have is this:

<?php

namespace App\Packages\Schedule;
use Spatie\OpeningHours\OpeningHours;
class Schedule extends OpeningHours
{
	//returns true if a business is open on all days passed in array
	//returns false if business is closed on any one of the days
	public function isOpenOnDays(array $days): bool
	{
    	$count_days = count($days);
    	for($i = 0; $i < $count_days; $i++) {
        	$v = $this->isOpenOn($days[$i]);
        	if($v == false) {
            	return false;
        	}
    	}
    	return $v;
	}
}

but if I have an instance of OpeningHours called $schedule, and I try to access $schedule->isOpenOnDays($days); I get this error:

Call to undefined method Spatie\OpeningHours\OpeningHours::isOpenOnDays()

I have tried to figure out how to extend the OpeningHours class and use the composer autoloader to get it to work but I can't figure it out.

0 likes
3 replies
drewdan's avatar
drewdan
Best Answer
Level 15

If you are extending the class, you will need to create an instance of the extended class instead of the spatie class.

$schedule = new Schedule();

$schedule->isOpenOnDays();
1 like
garrettmassey's avatar

@drewdan I just figured this out as I was trying a few different things. I extended the class properly, but failed to change the instance.

Thanks!

1 like

Please or to participate in this conversation.