Laravel,在Controller中使用外部类

问题描述 投票:0回答:1

我使用了类中的许多函数来在控制器中使用,这是防止代码重复的一种正常方法,但是我有一个函数可以将距离存储在模型中,并使用集合进行分页,该函数可以正常工作并返回控制器中的$ stores变量用于分页,现在我需要将其放在一个类中,然后从控制器中调用它,不幸的是它返回空值!我该如何解决这个问题?控制器中的相同功能工作正常,但是如果我将其放在一个类中并从控制器中调用将返回null,请帮助我

enter image description here

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);
php laravel
1个回答
0
投票
如果该功能对于多个控制器是通用的,请将其移至PHP特性。特性是专为可重用性目的而设计的。然后,您可以在控制器中使用该特征并像调用控制器功能一样调用其功能$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
© www.soinside.com 2019 - 2024. All rights reserved.