2014-10-06 105 views
0

在Laravel 5中,我尝试将MyClass添加到IoC容器中。在IoC容器上注册时找不到Laravel 5中的类

所以我加了如下结构:

应用程序/利布斯/ MyClass.php

<?php namespace App\Libs; 

use App\Interfaces\MyClassInterface; 

class MyClass implements MyClassInterface { 

    public function list($itemId) 
    { 
     // do any things 
    } 

} 

应用程序/幕墙/ MyClassFacade.php

<?php namespace App\Facades; 

use Illuminate\Support\Facades\Facade; 

class MyClassFacade extends Facade { 

     protected static function getFacadeAccessor() 
     { 
       return 'myclass'; 
     } 
} 

应用程序/ Providers/MyClassServiceProvider.php

<?php namespace App\Providers; 

use Illuminate\Support\ServiceProvider; 

use App\Libs\MyClass; 
class MyClassServiceProvider extends ServiceProvider { 
    public function boot() 
    { 
     // 
    } 
    public function register() 
    { 
     $this->app->bind('myclass', function() { 
      return new MyClass(); 
     }); 
    } 
} 

应用/配置/ app.php(在供应商)

'App\Providers\MyClassServiceProvider', 

应用/配置/ app.php(别名)

'MyClass' => 'App\Facades\MyClassFacade', 

应用程序/ Http/Controllers/MyClassController.php

<?php namespace App\Http\Controllers; 

class MyClassController { 

public function index($itemId = null) 
{ 
    $itemList = MyClass::list($itemId); // this is line error 

    return view('item.list')->with($itemList); 
} 

应用程序/ HTTP/routes.php文件

Route::pattern('numeric', '[0-9]+'); 
Route::get('item/{numeric?}', array('as' => 'item_list', 'uses' => '[email protected]')); 

然后我跑的命令

composer update 

composer dump-autoload 

但是赠品我得到这个错误:

Class 'App\Http\Controllers\MyClass' not found 

我哪里错了?

回答

1

与错误的行你需要使用:的

$itemList = \MyClass::list($itemId); // this is line error 

代替:

$itemList = MyClass::list($itemId); // this is line error 

或更改该文件到:

<?php namespace App\Http\Controllers; 

use MyClass; 

class MyClassController { 

public function index($itemId = null) 
{ 
    $itemList = MyClass::list($itemId); // this is line error 

    return view('item.list')->with($itemList); 
} 

这不是Laravel具体问题。这是你如何使用命名空间。更多在How to use objects from other namespaces and how to import namespaces in PHP

+0

我不能那样做Marcin,因为那样你告诉MyClass类应该是一个静态类。我知道,因为这个对象有个别名,容器会处理剩下的事情。 – JulianoMartins 2014-10-06 19:17:12

+0

@JulianoMartins不是。如果你在这里使用'MyClass ::',你告诉PHP你想从当前命名空间使用MyClass。解决这个问题的唯一方法是添加主要的反斜杠,以便在全局命名空间中告诉该类(如您定义的别名)或使用使用'use'导入命名空间。如果Controller不在全局名称空间中,则没有其他方法。 – 2014-10-06 19:19:53

+0

MarcinNabiałek,你是对的。现在效果很好!谢谢! – JulianoMartins 2014-10-06 19:25:28