php - Laravel:从另一个位置调用 Controller 方法

标签 php oop laravel laravel-5

在我的 Laravel 应用程序中,我有以下 Controller ,它将 Elastic search 的实例作为第一个参数,然后是另一个变量:

use Elasticsearch\Client;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class AngularController extends Controller {
    public function selectRandom(Client $es, $numRows) {
        # ...search params here
        $results = $es->search($searchParams);
        return $results;
    }
}

我需要从另一个 Controller 调用上面 Controller 的方法,我这样做:

class HomeCtrl extends Controller {

    public function index() {

        $featured = new AngularController();

        return $featured->selectRandom(12);
    }

}

我收到以下错误

Argument 1 passed to App\Http\Controllers\AngularController::selectRandom() must be an instance of Elasticsearch\Client, integer given

我不太熟悉 OOP。我调用它不正确吗?因为我认为我调用的方法会采用注入(inject)到 Controller 中的实例,而不是从我调用它的地方。

最佳答案

When you are calling a method from your Controller to another Controller that means you are doing wrong. For this purpose you should use service.

在app\Services Utility.php中创建一个类

use Elasticsearch\Client;

class Utility {

    public function selectRandom(Client $es, $numRows) {
        # ...search params here
        $results = $es->search($searchParams);
        return $results;
    }
}

and just inject this class to your controller

关于php - Laravel:从另一个位置调用 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32310504/

相关文章:

php - Laravel 4 队列 :listen times out

laravel - 从前 100 行中随机抽取 10 行

php - Laravel 4 - 从包中扩展应用程序 Controller

perl - 我可以在Perl中动态指定的类中访问静态方法吗?

php - 在 PHP 中调用父级的构造函数

php - 防止UUID冲突

php - 显示以逗号分隔的数据库条目

java - 如何通过构造函数中的依赖注入(inject)而不使用框架来应用记录器

php - 具有固定参数值的路由的别名

php - 为什么在 composer 中更新依赖项这么慢?