【发布时间】:2013-02-20 15:01:26
【问题描述】:
这与How to register a namespace in laravel 4 这个问题有关,但我相信我已经解决了这个问题,并且命名空间现在正在工作。
我遇到了一个新问题。我相信错误来自尝试在控制器构造函数中键入提示,并且与使用命名空间和使用 ioc 有关。
BindingResolutionException: Target [App\Models\Interfaces\PostRepositoryInterface] is not instantiable.
在我尝试引入命名空间之前,以下方法运行良好。我可以删除所有命名空间并将接口和存储库放在同一目录中,但想知道如何使命名空间与这种使用 ioc 的方法一起工作。
这里是相关文件。
routes.php
Route::resource('posts', 'PostsController');
PostController.php
<?php
use App\Models\Interfaces\PostRepositoryInterface;
class PostsController extends BaseController {
public function __construct( PostRepositoryInterface $posts )
{
$this->posts = $posts;
}
}
PostRepositoryInterface.php
<?php namespace App\Models\Interfaces;
interface PostRepositoryInterface {
public function all();
public function find($id);
public function store($data);
}
EloquentPostRepository.php
<?php namespace App\Models\Repositories;
use App\Models\Interfaces\PostRepositoryInterface;
class EloquentPostRepository implements PostRepositoryInterface {
public function all()
{
return Post::all();
//after above edit it works to this point
//error: App\Models\Repositories\Post not found
//because Post is not in this namespace
}
public function find($id)
{
return Post::find($id);
}
public function store($data)
{
return Post::save($data);
}
}
你可以看到 composer dump-autoload 完成了它的工作。
作曲家/autoload_classmap.php
return array(
'App\\Models\\Interfaces\\PostRepositoryInterface' => $baseDir . '/app/models/interfaces/PostRepositoryInterface.php',
'App\\Models\\Repositories\\EloquentPostRepository' => $baseDir . '/app/models/repositories/EloquentPostRepository.php',
....
)
任何想法我需要改变什么地方或什么地方才能使它与命名空间一起工作,就像没有它们一样?
谢谢
【问题讨论】:
-
我已经克服了第一个错误。我不知道 App::bind() 是如何工作的,但是将整个命名空间作为字符串传递是有效的。我将更新那部分代码。现在问题出在 EloquentPostRepository 中,因为它是命名空间的,当我尝试调用 Post::all() 时,它会将“Post”放在“Repositories”命名空间中。需要弄清楚如何在命名空间之外调用一个类。
标签: namespaces ioc-container laravel laravel-4