Silex 中 ControllerResolver 中的 InvalidArgumentException

InvalidArgumentException in ControllerResolver in Silex

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

我用这个 silex-bootstrap : https://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.

我该怎么办?

您正在尝试使用控制器 提供者 作为实际控制器。这是两个不同的东西。提供商只需向您的 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());