Silex中ControllerResolver中的InvalidArgumentException

时间:2015-03-27 12:43:35

标签: php controller silex

我是使用框架和Silex的新手, 我尝试与Silex合作并编写我的第一个项目。

我使用此silex-bootstraphttps://github.com/fbrandel/silex-boilerplate

现在在app/app.php

<?php
require __DIR__.'/bootstrap.php';

$app = new Silex\Application();
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
// Twig Extension
$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/views',
));

// Config Extension
$app->register(new Igorw\Silex\ConfigServiceProvider(__DIR__."/config/config.yml"));

$app->get('/admin', new App\Controller\Admin\AdminDashboard());

return $app;

app/Controller/Admin/AdminDashboard.php

<?php


namespace App\Controller\Admin;

use Silex\Application;
use Silex\ControllerProviderInterface;
use Silex\ControllerCollection;

class AdminDashboard implements ControllerProviderInterface {


    function __construct()
    {
        return "Dashboard";

    }

    function index()
    {
        return "Index Dashboard";
    }

    public function connect(Application $app)
    {
        return "OK";
    }


}

当我尝试访问网站时出现此错误: http://localhost/project/public

InvalidArgumentException in ControllerResolver.php line 69:
Controller "App\Controller\Admin\AdminDashboard" for URI "/admin" is not callable.

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您尝试使用控制器提供程序作为实际控制器。这是两件不同的事情。提供程序只需使用您的silex应用程序注册控制器。您的提供商应该看起来像这样:

namespace App\Controller\Admin;

use Silex\Application;
use Silex\ControllerProviderInterface;

class AdminDashboardProvider implements ControllerProviderInterface
{
    public function connect(Application $app)
    {
        $controllers = $app['controllers_factory']();

        $controllers->get('/', function() {
            return 'Index Dashboard';
        });

        return $controllers;
    }
}

然后,您应该将该控制器提供程序安装到app/app.php中的应用程序。

$app->mount('/admin', new AdminDashboardProvider());

显然,一旦你获得了多个控制器或你的控制器变大,这就不是很优雅了。这就是ServiceControllerServiceProvider所在的位置。它允许您的控制器成为单独的类。我通常使用这样的模式:

<?php
namespace App\Controller\Admin;

use Silex\Application;
use Silex\ControllerProviderInterface;

class AdminDashboardProvider implements ControllerProviderInterface, ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['controller.admin.index'] = $app->share(function () {
            return new AdminIndexController();
        });
    }

    public function connect(Application $app)
    {
        $controllers = $app['controllers_factory']();

        $controllers->get('/', 'controller.admin.index:get');

        return $controllers;
    }

    public function boot(Application $app)
    {
        $app->mount('/admin', $this);
    }
}

控制器如下所示:

namespace App\Controller\Admin;

class AdminIndexController
{
    public function get()
    {
        return 'Index Dashboard';
    }
}

然后,您可以在app/app.php中将您的应用注册为:

$app->register(new AdminDashboardProvider());