2015-02-25 11:48 阅读 33


I'm trying to deepen my knowlade in laravel architecture.

  1. I have a search engine (elastic search for the sake of the example), but this search engine might change in the future. So im trying to write a container for this, so in case i'll change the engine in the future, i will have to change only the container. (I believe the termenology is factory design?)

  2. I have created a provider app/providers/DataFromSearchEngine.php that looks like this:

    use Illuminate\Support\ServiceProvider;
    class DataFromSearchEngine extends ServiceProvider {
       public function boot()
       public function register()
        $this->app->singleton('SearchEngine', function($app) {
           return new elasticSearch; 
  3. Then i registered it in the providers array in config/app.php .

    'providers' => [
        // providers...
  4. The next step is to call SearchEngine from my controller:

    namespace App\Http\Controllers;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    class SearchController extends Controller {
       protected $searchEngine;
       public function __construct() {
          $this->searchEngine = $this->app->make('SearchEngine');

But all these yields: Undefined property: App\Http\Controllers\SearchController::$app

Can someone explain what i'm missing?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duandongji2231 duandongji2231 2015-02-25 12:13

    Instead of using $this->app try using app().

    This is because non of the inherited controller classes, i.e. App\Http\Controllers\Controller or Illuminate\Routing\Controllers\Controller have an app property on them.

    As a note you can use app('SearchEngine') which is the equivalent of app()->make('SearchEngine') as a shortcut to making your object.

    点赞 评论 复制链接分享