您好。我是Silex(2.0)的新手,我试图将$ app变量传递给我的Controller,因此我尝试将Controller作为服务创建。
我正在关注documentation guide,但在注册我的控制器时,我收到类型错误:InvalidArgumentException:Class" controller。默认"不存在。
在我的index.php上:
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
// Register controller as services.
$app['controller.default'] = function() use ($app) {
return new Fortunio\Controller\DefaultController($app);
};
$app->get('/', "controller.default::indexAction");
如果我更改最后一行代码,应用程序运行顺利,错误消失:
$app->get('/', 'Fortunio\Controller\DefaultController::indexAction');
在我的控制器上:
<?php
namespace Fortunio\Controller;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
class DefaultController
{
public function indexAction(Application $app, Request $request)
{
// my controller code here
}
}
我的错误在哪儿?
提前谢谢。
答案 0 :(得分:1)
首先:很好地汇总问题。
据我所知,你可以看到你的文档,所以如果他们声称应该工作:你的代码应该有效。也就是说,这是不我们使用控制器作为服务的方法。我们的方法更像是这样:
class ControllerProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['controller.thing'] = function ($app) {
return new ThingController();
};
}
}
class RouteProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app->get('/thing/{id}/', function (Request $request) use ($app) {
return $app['controller.thing']->doGET($request);
})->assert('id', '\d+');
}
}
use Silex\Application as SilexApplication;
class Application extends SilexApplication
{
public function __construct()
{
$this->register(new ControllerProvider());
$this->register(new RouteProvider());
}
}
$app = new Application();
关键区别在于此位,在RouteProvider中:
$app->get('/thing/{id}/', function (Request $request) use ($app) {
return $app['controller.thing']->doGET($request);
})->assert('id', '\d+');
看到我们不使用对控制器服务的字符串引用(即:只是controller.thing:doGET
),我们使用对DI容器中控制器的实际引用,并实际调用闭包中的方法。 / p>
我想检查他们的文档版本是否真的有效,但我需要回到我的日常工作。我稍后会对它进行调整,并回过头来判断我是否正常工作。我确定有过去使用controller.thing:doGET
方法,但即便如此,我的方法(使用Silex 1.x)也略有不同。这是一篇博客文章:PHP: Silex Controller Providers,但我不再推荐这种方法了。我将它包括在内只是为了证明该语法可以起作用。