dpu66046 2015-02-25 11:48 采纳率: 0%
浏览 38
已采纳

尝试从IOC容器实例化依赖项时未定义的属性异常

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...
    
        'App\Providers\DataFromSearchEngine'
    ],
    
  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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据