我使用了类中的许多函数来在控制器中使用,这是防止代码重复的一种正常方法,但是我有一个函数可以将距离存储在模型中,并使用集合进行分页,该函数可以正常工作并返回控制器中的$ stores变量用于分页,现在我需要将其放在一个类中,然后从控制器中调用它,不幸的是它返回空值!我该如何解决这个问题?控制器中的相同功能工作正常,但是如果我将其放在一个类中并从控制器中调用将返回null,请帮助我
Class:
public function getStoresDistance($allstores)
{
$stores = collect([]);
foreach (session('storeinfo') as $storeInfo) {
$store = $allstores->find($storeInfo['id']);
if ($store) {
$store->distance = $storeInfo['distance'];
$stores[] = $store;
if (!Collection::hasMacro('paginate')) {
Collection::macro('paginate', function ($perPage = 25, $page = null, $options = []) {
$options['path'] = $options['path'] ?? request()->path();
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
return new LengthAwarePaginator(
$this->forPage($page, $perPage)->values(),
$this->count(),
$perPage,
$page,
$options
);
});
}
}
}
}
来自控制器的呼叫:
$allstores = Storeinfo::where('show', 'y')->get();
$findstores = Helper::getStoresDistance($allstores);
$this->yourFunction()
。下面是您的代码外观:特质:
trait StoresDistance
{
public function storesDistance(){}
}
Controller:
class YourController extends Controller
{
use StoresDistance;
public function getStoresDistance($allstores)
{
// some code
$this->storesDistance();
// some code
}
}
参考文档:https://www.php.net/manual/en/language.oop5.traits.php