应用程序/配置/ routing.php
这是应该如何做的
$collection = new RouteCollection();
$collection->addCollection(
// second argument is the type, which is required to enable
// the annotation reader for this resource
$loader->import("@AppBundle/Controller/", "annotation")
);
return $this->collection;
我需要为公司创建一个更复杂的路由系统, 并且需要能够在班级中注册路线。
class AutoRouter extends AppKernel
{
function __construct()
{
}
public function registerControllers()
{
$collection = new RouteCollection();
global $loader;
$collection->addCollection(
// second argument is the type, which is required to enable
// the annotation reader for this resource
$loader->import("@AppBundle/Controller/", "annotation")
);
return $this->collection;
}
//(....)
}
tldr;我需要从registerControllers方法访问import函数,但它会抛出此错误
UndefinedMethodException:尝试调用方法" import"在课堂上 "作曲\自动加载\类加载器"
// Answer
use Symfony\Component\Routing\RouteCollection;
class AutoRouter extends AppKernel
{
private $collection;
public function registerControllers($loader)
{
$collection = new RouteCollection();
$collection->addCollection(
// second argument is the type, which is required to enable
// the annotation reader for this resource
$loader->import("@AppBundle/Controller/", "annotation")
);
return $this->collection;
}
public function getActiveBundles()
{
return $this->registerBundles();
}
}
$at = new AutoRouter('dev', true);
return $at->registerControllers($loader);
答案 0 :(得分:1)
这是利用dependency injection的绝佳机会。您应该将public IQueryable<User> GetAll() {
const string query = @"
select * from [dbo].[User]
";
return this._db.Query<User>(query, new {}).AsQueryable();
}
实例作为类型提示参数注入,以确保提供正确的对象实例。
$loader
使用依赖注入还可以更容易地在将来更改具体实现,而无需更改“消费”。代码。
快乐的编码!